Geo*_*ina 10 python loops for-loop continue
基本上,我需要一种方法将控制返回到for循环的开头,并且如果满足某个条件,则在采取操作后实际重新启动整个迭代过程.
我想要做的是这样的:
for index, item in enumerate(list2):
if item == '||' and list2[index-1] == '||':
del list2[index]
*<some action that resarts the whole process>*
Run Code Online (Sandbox Code Playgroud)
这样,如果['berry','||','||','||','pancake'在列表中,我将结束:
['berry','||','pancake']相反.
谢谢!
Liq*_*ire 34
我不确定"重启"是什么意思.您想从头开始迭代,还是只是跳过当前的迭代?
如果它是后者,那么for循环支持continue就像while循环一样:
for i in xrange(10):
if i == 5:
continue
print i
Run Code Online (Sandbox Code Playgroud)
以上将打印0到9之间的数字,5除外.
如果你正在谈论从for循环开始重新开始,除了"手动"之外没有办法做到这一点,例如将它包装在一个while循环中:
should_restart = True
while should_restart:
should_restart = False
for i in xrange(10):
print i
if i == 5:
should_restart = True
break
Run Code Online (Sandbox Code Playgroud)
上面将打印从0到5的数字,然后从0开始重新开始,依此类推(不是一个很好的例子,我知道).
nmi*_*els 25
while True:
for i in xrange(10):
if condition(i):
break
else:
break
Run Code Online (Sandbox Code Playgroud)
这将做你想要的.为什么你想要这样做是另一回事.也许你应该看看你的代码,并确保你没有错过一个明显和简单的方法来做到这一点.
一些动作可以重新启动整个过程
一种思考算法的糟糕方式.
你只是过滤,即删除重复.
并且 - 在Python中 - 你最快乐地制作副本,而不是试图做del.一般来说,使用的呼叫很少del.
def unique( some_list ):
list_iter= iter(some_list)
prev= list_iter.next()
for item in list_iter:
if item != prev:
yield prev
prev= item
yield prev
list( unique( ['berry','||','||','||','pancake'] ) )
Run Code Online (Sandbox Code Playgroud)