<p>我正在尝试生成一个代码,可以遍历列表中的所有项目,这里:</p>
<pre><code>def lunch():
global tl
print("You have %s minutes until school starts." % (tl))
go=True
lunch=["pasta","pb+j","chicken","cheez its","goldfish","pirate's booty","cookie","cupcake","gogurt","strawberries","apple","grapes","carrots","bell peppers","pea pods"]
a=0
while a<len(lunch)-4:
print("Do you pack or buy your lunch? (p,b)")
lunch=input()
if lunch=="pack" or lunch=="p":
go2=True
while go2:
print("Do you want %s, %s, or %s?" % (lunch[a],lunch[a+1],lunch[a+2]))
l=input()
if not(l==lunch[a] or l==lunch[a+1] or l==lunch[a+2]):
print("What?")
else:
print("Yay!")
go2=False
a+=3
</code></pre>
<p>但我一直得到错误“IndexError:string index out of range”的行</p>
^{pr2}$
<p>我知道这意味着索引大于或小于它可以索引的值(大于或小于列表的长度减去1),但它不应该这样做,因为它从0开始,在列表结束之前结束于4。在</p>
<p>您的问题是对<code>lunch[a+n]</code>中索引的引用超出了范围。你可以这样代表你的选择。在</p>
<pre><code>lunch = ['pasta', 'pudding', 'cereal', 'steak']
print('Would you like {0} or {1} or {2} or {3}'.format(*lunch))
</code></pre>