重复当前循环迭代而不进入下一次迭代的最佳方法是什么?

问题描述 投票:0回答:1

有时在

for
循环中,我希望能够从头开始重复当前迭代,类似这样:

for element in list:
    # top of for
    ...
    if condition:
        ...
        repeat # that would make the current iteration restart from the top
               # without getting the next element in the list

我通常用

while
内的
for
来模拟这种行为:

for element in list:
    while True:
        # top of while=top of for 
        ...
        if condition:
            ...
            continue # repeat: go to the top of the while
        ...
        # last line inside the while will break the while 
        break

有更好的方法吗?

python loops repeat
1个回答
0
投票

如果可能的话,我会将嵌套循环放在私有函数中。这样会更清楚。另一种选择是迭代列表

iter_list = iter(list)
value = next(iter_list,None)
while value is not None: # you reached the end of the iterator
    ....
    if not condition:
        value = next(iter_list,None)
        continue # condition isn't met skip to the next item
© www.soinside.com 2019 - 2024. All rights reserved.