相关疑难解决方法(0)

for循环中的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
Run Code Online (Sandbox Code Playgroud)

运行时,输出:

 [ ] Option 0
 [ ] Option 1 …
Run Code Online (Sandbox Code Playgroud)

python loops for-loop

138
推荐指数
2
解决办法
28万
查看次数

标签 统计

for-loop ×1

loops ×1

python ×1