Python - 重新启动 for 循环的方法,类似于 while 循环的“继续”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3704918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Way to restart a for loop, similar to "continue" for while loops?
提问by Georgina
Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration processafter taking an action if a certain condition is met.
基本上,我需要一种方法将控制权返回到 for 循环的开头,并在满足某个条件时在采取行动后实际重新启动整个迭代过程。
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] 在列表中,我会得到:
['berry','||','pancake'] instead.
['berry','||','pancake'] 代替。
Thanks!
谢谢!
采纳答案by Liquid_Fire
I'm not sure what you mean by "restarting". Do you want to start iterating over from the beginning, or simply skip the current iteration?
我不确定您所说的“重新启动”是什么意思。你想从头开始迭代,还是直接跳过当前的迭代?
If it's the latter, then forloops support continuejust like whileloops do:
如果是后者,则for循环支持continue就像while循环一样:
for i in xrange(10):
if i == 5:
continue
print i
The above will print the numbers from 0 to 9, except for 5.
以上将打印从 0 到 9 的数字,除了 5。
If you're talking about starting over from the beginning of the forloop, there's no way to do that except "manually", for example by wrapping it in a whileloop:
如果您正在谈论从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
The above will print the numbers from 0 to 5, then start over from 0 again, and so on indefinitely (not really a great example, I know).
上面将打印从 0 到 5 的数字,然后再次从 0 开始,依此类推(我知道这不是一个很好的例子)。
回答by volting
Continuewill work for any loop.
Continue将适用于任何循环。
回答by Sam Dolan
continueworks in for loops also.
continue也适用于 for 循环。
>>> 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
回答by nmichaels
while True:
for i in xrange(10):
if condition(i):
break
else:
break
That will do what you seem to want. Why you would want to do it is a different matter. Maybe you should take a look at your code and make sure you're not missing an obvious and easier way to do it.
这将做你似乎想要的。你为什么要这样做是另一回事。也许您应该查看一下您的代码,并确保您没有遗漏一种明显且更简单的方法。
回答by S.Lott
some action that resarts the whole process
一些重新启动整个过程的动作
A poor way to think of an algorithm.
一种思考算法的糟糕方式。
You're just filtering, i.e., removing duplicates.
您只是在过滤,即删除重复项。
And -- in Python -- you're happiest making copies, not trying to do del. In general, there's very little call to use del.
而且——在 Python 中——你最高兴的是制作副本,而不是试图去做del。一般来说,很少有调用 use 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'] ) )
回答by Jochen Ritzel
The inevitable itertools version, because it just came to me:
不可避免的 itertools 版本,因为它刚刚来到我身边:
from itertools import groupby
def uniq(seq):
for key, items in groupby(seq):
yield key
print list(uniq(['berry','||','||','||','pancake'])) # ['berry','||', 'pancake']
# or simply:
print [key for key, items in groupby(['berry','||','||','||','pancake'])]
回答by Tony Veijalainen
def remove_adjacent(nums):
return [a for a,b in zip(nums, nums[1:]+[not nums[-1]]) if a != b]
example = ['berry','||','||','||','pancake']
example = remove_adjacent(example)
print example
""" Output:
['berry', '||', 'pancake']
"""
And by the way this is repeating of Remove adjacent duplicate elements from a list
回答by John La Rooy
As you can see answering your question leads to some rather convoluted code. Usually a better way can be found, which is why such constructs aren't built into the language
正如您所看到的,回答您的问题会导致一些相当复杂的代码。通常可以找到更好的方法,这就是为什么这种结构没有内置到语言中的原因
If you are not comfortable using itertools, consider using this loop instead. Not only is it easier to follow than your restarting for loop, it is also more efficient because it doesn't waste time rechecking items that have already been passed over.
如果您不习惯使用 itertools,请考虑改用此循环。不仅比重新启动 for 循环更容易遵循,而且效率也更高,因为它不会浪费时间重新检查已经传递的项目。
L = ['berry','||','||','||','pancake']
idx=1
while idx<len(L):
if L[idx-1]==L[idx]:
del L[idx]
else:
idx+=1

