【问题标题】:Changing the index of a For loop in Python (outside if statement) [duplicate]在 Python 中更改 For 循环的索引(在 if 语句之外)[重复]
【发布时间】:2020-01-21 13:04:32
【问题描述】:

我正在尝试更改 for 循环的索引,具体取决于用户是否要转到上一个图像(索引 = 索引 - 1)以及他是否要转到下一个图像(索引 = 索引 + 1),但是,索引在外循环中没有变化(在 if 语句之外)。

flag = False
while flag == False:
    for i in range(len(all_image)):

        image = all_image[i]
        print(i)
        userchoice = easygui.buttonbox(msg, image = image, choices=choices)

        if userchoice == 'Next':
            i = i+1

        elif userchoice == 'Previous':
            i = i-1

        elif userchoice == 'cancel':
            print('test')
            flag = True
            break       

提前致谢。

【问题讨论】:

  • 你不能用for-loop 做到这一点。它总是会从range() 获取下一个值。
  • 就是这样:你不能用 for 循环来做到这一点 - 你需要一个 while 循环

标签: python python-3.x for-loop


【解决方案1】:

不确定为什么会有 for 循环,我很想将它的结构更像这样:

flag = False
idx = 0 #idx is where we are in the image list, and it gets modified by use choices in the while loop.
while flag == False:
    image = all_image[idx]
    print(idx)
    userchoice = easygui.buttonbox(msg, image = image, choices=choices)

    if userchoice == 'Next':
        idx += 1
    elif userchoice == 'Previous':
        idx -= 1
    elif userchoice == 'cancel':
        print('test')
        flag = True
        break       

【讨论】:

  • 谢谢!该解决方案有效。是的,现在看,我不确定我为什么要包含一个 For 循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 2019-01-21
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多