简介:
所以我知道已经有一个与我类似的问题( Skip multiple iterations in loop )有一个非常好的答案,但我仍然有一些悬而未决的问题:
问题 1:
有没有办法在没有迭代器的情况下做到这一点?
我正在寻找类似 * 3 的内容:song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
for sing in song:
print(sing, end=" ")
if sing == 'look':
continue * 3
预期输出:
always look side of life
问题 2:
如果我必须使用迭代器对象,那么是否可以在固定的时间内完成它?
原来的问题有这样的解决方案:
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(next(song_iter))
但我希望它执行 x = 5 次。这是不可能的:
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) * x
print(next(song_iter))
那么你会怎么做呢?我知道可以使用函数 itertools.<b>islice</b>
,但是有没有没有任何库的方法呢?
我的方法:
这很好用:song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
skip_iterations = 3
for sing in song_iter:
print(sing)
if sing == "look":
while skip_iterations > 0:
next(song_iter, "")
skip_iterations -= 1
输出:
always look side of life
但也许其他人有更好的主意? :)
链接:
The Question I was mentioning - The Answer for that question
最佳答案
Ans 1 有很多方法可以解决这个问题,最简单的方法之一是检查索引,例如
song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
skip_iterations=3
for i,sing in enumerate(song):
if not song.index('look') < i < song.index('look')+skip_iterations+1:
print(sing, end=" ")
“枚举”返回(索引,元素) Ans 2 你的方法很好,你可能更喜欢 for 循环而不是 while 循环,但这只是个人建议。
关于python - Python 中是否可以在循环中跳过固定次数的迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70413412/