Python for循环中的循环计数器 [英] Python loop counter in a for loop

查看:226
本文介绍了Python for循环中的循环计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我下面的示例代码中,计数器= 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,尽管我仍然对

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

运行时输出:

When run, it outputs:

 [ ] 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),如果你想,但它们是无关的,通常不包括在内。

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

这篇关于Python for循环中的循环计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆