我会遍历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
优化
如果您正在跳过 maaaaaaany 迭代,那么此时listifying 结果将变得内存效率低下。尝试迭代消费z:
for el in z:
print(el)
if el == 4:
for _ in xrange(3): # Skip the next 3 iterations.
next(z)
感谢@Netwave 的建议。
如果您也需要索引,请考虑将iter 包裹在enumerate(z) 调用周围(对于python2.7....对于python-3.x,不需要iter)。
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