Python 在循环中跳过多次迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22295901/
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
Skip multiple iterations in loop
提问by Mehdi Nellen
I have a list in a loop and I want to skip 3 elements after lookhas been reached.
In this answera couple of suggestions were made but I fail to make good use of them:
我有一个循环列表,我想look在到达后跳过 3 个元素。在这个答案中提出了一些建议,但我没有很好地利用它们:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
for sing in song:
if sing == 'look':
print sing
continue
continue
continue
continue
print 'a' + sing
print sing
Four times continueis nonsense of course and using four times next()doesn't work.
四次continue当然是无稽之谈,使用四次next()是行不通的。
The output should look like:
输出应如下所示:
always
look
aside
of
life
采纳答案by Martijn Pieters
foruses iter(song)to loop; you can do this in your own code and then advance the iterator inside the loop; calling iter()on the iterable again will only return the same iterable object so you can advance the iterable inside the loop with forfollowing right along in the next iteration.
for用于iter(song)循环;您可以在自己的代码中执行此操作,然后在循环内推进迭代器;iter()再次调用可迭代对象只会返回相同的可迭代对象,因此您可以在循环内推进可迭代对象for,并在下一次迭代中继续进行。
Advance the iterator with the next()function; it works correctly in both Python 2 and 3 without having to adjust syntax:
使用next()函数推进迭代器;它在 Python 2 和 3 中都可以正常工作,而无需调整语法:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
next(song_iter)
next(song_iter)
next(song_iter)
print 'a' + next(song_iter)
By moving the print singline up we can avoid repeating ourselves too.
通过向上移动print sing队列,我们也可以避免重复自己。
Using next()this way canraise a StopIterationexception, if the iterable is out of values.
如果可迭代对象没有值,则使用next()这种方式会引发StopIteration异常。
You could catch that exception, but it'd be easier to give next()a second argument, a default value to ignore the exception and return the default instead:
您可以捕获该异常,但提供next()第二个参数会更容易,默认值可以忽略异常并返回默认值:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
next(song_iter, None)
next(song_iter, None)
next(song_iter, None)
print 'a' + next(song_iter, '')
I'd use itertools.islice()to skip 3 elements instead; saves repeated next()calls:
我习惯itertools.islice()跳过 3 个元素;保存重复next()调用:
from itertools import islice
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
print 'a' + next(islice(song_iter, 3, 4), '')
The islice(song_iter, 3, 4)iterable will skip 3 elements, then return the 4th, then be done. Calling next()on that object thus retrieves the 4th element from song_iter().
该islice(song_iter, 3, 4)迭代将跳过3个元素,然后返回4,然后来完成。next()因此,调用该对象会从 中检索第 4 个元素song_iter()。
Demo:
演示:
>>> from itertools import islice
>>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
>>> song_iter = iter(song)
>>> for sing in song_iter:
... print sing
... if sing == 'look':
... print 'a' + next(islice(song_iter, 3, 4), '')
...
always
look
aside
of
life
回答by radomaj
Actually, using .next() three times is not nonsense. When you want to skip n values, call next() n+1 times (don't forget to assign the value of the last call to something) and then "call" continue.
实际上,使用 .next() 三次并不是无稽之谈。当您想跳过 n 个值时,调用 next() n+1 次(不要忘记将上次调用的值分配给某物)然后“调用”继续。
To get an exact replica of the code you posted:
要获取您发布的代码的精确副本:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
songiter = iter(song)
for sing in songiter:
if sing == 'look':
print sing
songiter.next()
songiter.next()
songiter.next()
sing = songiter.next()
print 'a' + sing
continue
print sing
回答by hivert
Of course you can use three time next (here I actually do it four time)
当然你接下来可以用3次(这里我实际上是用了4次)
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
it = iter(song)
for sing in it:
if sing == 'look':
print sing
try:
sing = it.next(); sing = it.next(); sing = it.next(); sing=it.next()
except StopIteration:
break
print 'a'+sing
else:
print sing
Then
然后
always
look
aside
of
life
回答by bereal
I think, it's just fine to use iterators and nexthere:
我认为,next在这里使用迭代器就好了:
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
it = iter(song)
while True:
word = next(it, None)
if not word:
break
print word
if word == 'look':
for _ in range(4): # skip 3 and take 4th
word = next(it, None)
if word:
print 'a' + word
or, with exception handling (which is shorter as well as more robust as @Steinar noticed):
或者,使用异常处理(正如@Steinar 注意到的那样,它更短也更健壮):
it = iter(song)
while True:
try:
word = next(it)
print word
if word == 'look':
for _ in range(4):
word = next(it)
print 'a' + word
except StopIteration:
break
回答by SaeX
You can do this without an iter() as well simply using an extra variable:
您可以在没有 iter() 的情况下执行此操作,也只需使用额外的变量即可:
skipcount = -1
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
for sing in song:
if sing == 'look' and skipcount <= 0:
print sing
skipcount = 3
elif skipcount > 0:
skipcount = skipcount - 1
continue
elif skipcount == 0:
print 'a' + sing
skipcount = skipcount - 1
else:
print sing
skipcount = skipcount - 1
回答by demo.b
>>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
>>> count = 0
>>> while count < (len(song)):
if song[count] == "look" :
print song[count]
count += 4
song[count] = 'a' + song[count]
continue
print song[count]
count += 1
Output:
always
look
aside
of
life

