for循环中的Python循环计数器 [英] Python loop counter in a for loop
问题描述
在我下面的示例代码中,是否真的需要 counter = 0,或者是否有更好、更 Python 的方法来访问循环计数器?我看到了一些与循环计数器相关的 PEP,但它们要么被推迟,要么被拒绝(PEP 212 和 PEP 281).
In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected (PEP 212 and PEP 281).
这是我的问题的一个简化示例.在我的实际应用程序中,这是通过图形完成的,并且必须在每一帧重新绘制整个菜单.但这以一种易于复制的简单文本方式展示了它.
This is a simplified example of my problem. In my real application this is done with graphics and the whole menu has to be repainted each frame. But this demonstrates it in a simple text way that is easy to reproduce.
也许我还应该补充一点,我使用的是 Python 2.5,尽管我仍然对是否有特定于 2.6 或更高版本的方法感兴趣.
Maybe I should also add that I'm using Python 2.5, although I'm still interested if there is a way specific to 2.6 or higher.
# Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
counter = 0
for option in options:
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
counter += 1
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(option, 2) # Draw menu with "Option2" selected
运行时输出:
[ ] Option 0
[ ] Option 1
[*] Option 2
[ ] Option 3
推荐答案
使用 enumerate()
像这样:
def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)
注意:如果需要,您可以选择将括号放在 counter, option
周围,例如 (counter, option)
,但它们是无关紧要的,通常不包括在内.
Note: You can optionally put parenthesis around counter, option
, like (counter, option)
, if you want, but they're extraneous and not normally included.
这篇关于for循环中的Python循环计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!