Python - Way to restart a for loop, similar to “co

2020-01-29 08:40发布

Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration process after taking an action if a certain condition is met.

What I'm trying to do is this:

    for index, item in enumerate(list2):
    if item == '||' and list2[index-1] == '||':
        del list2[index]
        *<some action that resarts the whole process>*

That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with:

['berry','||','pancake'] instead.

Thanks!

8条回答
ら.Afraid
2楼-- · 2020-01-29 09:32

continue works in for loops also.

>>> for i in range(3):
...     print 'Before', i
...     if i == 1:
...             continue
...     print 'After', i
... 
Before 0
After 0
Before 1
# After 1 is missing
Before 2
After 2
查看更多
时光不老,我们不散
3楼-- · 2020-01-29 09:40

Continue will work for any loop.

查看更多
登录 后发表回答