Python 跳过循环中的多个迭代
正在寻找允许跳过多个Python 跳过循环中的多个迭代,python,algorithm,python-2.7,list,iteration,Python,Algorithm,Python 2.7,List,Iteration,正在寻找允许跳过多个for循环,同时还具有当前索引的内容 在伪代码中,is看起来像这样: z = [1,2,3,4,5,6,7,8] for element in z: <calculations that need index> skip(3 iterations) if element == 5 z=[1,2,3,4,5,6,7,8] 对于z中的元素: 如果元素==5,则跳过(3次迭代) Python2中有这样的东西吗?为此,可以使用while循环 z =
for
循环,同时还具有当前索引的内容
在伪代码中,is看起来像这样:
z = [1,2,3,4,5,6,7,8]
for element in z:
<calculations that need index>
skip(3 iterations) if element == 5
z=[1,2,3,4,5,6,7,8]
对于z中的元素:
如果元素==5,则跳过(3次迭代)
Python2中有这样的东西吗?为此,可以使用while
循环
z = [1,2,3,4,5,6,7,8]
i = 0
while i < len(z):
# ... calculations that need index
if i == 5:
i += 3
continue
i += 1
z=[1,2,3,4,5,6,7,8]
i=0
而i
我会迭代iter(z)
,使用islice
将不需要的元素发送到遗忘。。。前
from itertools import islice
z = iter([1, 2, 3, 4, 5, 6, 7, 8])
for el in z:
print(el)
if el == 4:
_ = list(islice(z, 3)) # Skip the next 3 iterations.
# 1
# 2
# 3
# 4
# 8
优化
如果跳过任何迭代,那么此时list
如果跳过结果将导致内存效率低下。尝试反复使用z
:
for el in z:
print(el)
if el == 4:
for _ in xrange(3): # Skip the next 3 iterations.
next(z)
感谢@Netwave的建议
如果您也想要索引,请考虑包装<代码> ITER <代码>围绕<代码>枚举(z)< /Cord>调用(对于Python 2.7……对于Python 3.x,不需要<代码> ITER < /代码>)。
这实际上并没有跳过循环迭代。好的,看起来不错。顺便说一句,我没有投你反对票,但我希望投反对票的人能看到这一点并将其推翻。嗯,还有一个建议,你可能会错误地跳过一个额外的迭代,所以再看一次。生成一个“垃圾”列表看起来不是我认为最好的选择。也许用一个简单的循环来消耗它<对于xrange(3)中的uuu(z)
,顺便说一句,无需使用iter,因为islice
的行为类似于迭代器。我喜欢这个答案,但会颠倒顺序<代码>下一步第一步,列出(islice(…)
作为一种教育选择。
z = iter(enumerate([1, 2, 3, 4, 5, 6, 7, 8]))
for (idx, el) in z:
print(el)
if el == 4:
_ = list(islice(z, 3)) # Skip the next 3 iterations.
# 1
# 2
# 3
# 4
# 8