for循环中的Python循环计数器

时间:2009-07-26 21:05:26

标签: loops for-loop python

在我下面的示例代码中,是否真的需要counter = 0,还是有更好的,更多Python的方式来访问循环计数器?我看到一些与循环计数器相关的PEP,但它们被推迟或被拒绝(PEP 212PEP 281)。

这是我的问题的简化示例。在我的实际应用程序中,这是通过图形完成的,整个菜单必须在每一帧重新绘制。但这表明它以简单的文本方式易于重现。

也许我还应该补充一点,我正在使用Python 2.5,尽管如果有特定于2.6或更高版本的方式我仍然感兴趣。

# 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

4 个答案:

答案 0 :(得分:237)

如此使用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),但它们是无关的,通常不包括在内。

答案 1 :(得分:4)

你也可以这样做:

 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

如果有重复的选项,你会遇到问题。

答案 2 :(得分:4)

我有时会这样做:

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

虽然我倾向于避免这种情况,但这意味着我会多次说options[i]次。

答案 3 :(得分:1)

enumerate正是您要找的。

您可能也对unpacking感兴趣:

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

此外,还有itertools.count(),所以您可以执行类似

的操作
import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990