[英]Python 3.0: Looping list index that is “out of range”
好的,基本上,我將這個非常簡單的程序整合在一起需要一些幫助:
from graphics import *
def main():
win = GraphWin("Text Window", 400, 600)
options = ["Hello", "How", "Are", "You"]
x = 200
y = 20
for i in range(4):
message = Text(Point(x,y), options[i])
message.draw(win)
y = y + 30
main()
不用擔心“圖形”模塊。 它是John Zelle的Python書的一部分。 關鍵是我需要將范圍從5而不是4循環,但是,因為[i]中有'options',所以上面的特定程序會拉:
0: Hello
1: How
2: Are
3: You
4: ???
但是,如果我將4更改為5,它將在列表中查找第4個項目,但該項目不存在,因此它將吐出“ IndexError:列表索引超出范圍”
我要實現的是,當程序到達列表的末尾時,循環回到列表中的第一個(0)項。
例如,
for i in range(8):
將拉出:
0: Hello
1: How
2: Are
3: You
4: Hello
5: How
6: Are
7: You
我瀏覽了該站點,發現一些沒有成功的工具,其中包括“枚舉”功能,我認為這沒有幫助。
如果有人可以闡明如何做到這一點,將非常歡迎! 希望我能在沒有嵌套循環的情況下做到這一點。 預先感謝您的幫助。
您可以通過以下兩種方式之一來實現:
itertools.cycle
c = itertools.cycle(options)
for i in range(anyNumber):
message = Text(Point(x,y), next(c))
message.draw(win)
y = y + 30
for i in range(anyNumber):
message = Text(Point(x,y), options[i%len(options)])
message.draw(win)
y = y + 30
編輯 :
從對話中的評論:
如果要打印列表內容四次,可以通過以下兩種方法完成此操作:
options = ["Hello", "How", "Are", "You"]
for i in range(4):
for e,elem in enumerate(options):
print("%d: %s" %(4*i+e, elem))
要么
options = ["Hello", "How", "Are", "You"]
for e,elem in enumerate(itertools.chain.from_iterable(itertools.repeat(options,4))):
print("%d: %s" %(e, elem))
要么
options = ["Hello", "How", "Are", "You"]
for i in range(4):
for j in range(len(options)):
print("%d: %s" %(4*i+j, options[j]))
像這樣嗎
from itertools import cycle, islice
options = ["Hello", "How", "Are", "You"]
for idx, option in enumerate(islice(cycle(options), 8)):
print idx, option
首先循環值,而不是索引。 Python旨在避免使用索引循環,這樣做笨拙,效率低下且難看:
for option in options:
do_something(option)
遠勝於:
for option_index in range(len(options)):
do_something(options[option_index])
要獲取循環行為,請查看itertools.cycle() :
for option, _ in zip(itertools.cycle(options), range(x)):
...
其中x
是所需的項目數。 在這里,我們使用range()
和zip()
在達到項目數后停止重復(將范圍內的值扔掉)。
您可以使用模(%)運算符:
options = ["Hello", "How", "Are", "You"]
for i in range(8):
print(options[i % len(options)])
產量
Hello
How
Are
You
Hello
How
Are
You
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.