Igo*_* T. 4 python iteration algorithm list python-2.7
寻找允许跳过多个for循环同时还有当前index可用的东西.
在伪代码中,看起来像这样:
z = [1,2,3,4,5,6,7,8]
for element in z:
<calculations that need index>
skip(3 iterations) if element == 5
Run Code Online (Sandbox Code Playgroud)
Python 2中有这样的东西吗?
我会迭代iter(z),使用islice将不需要的元素发送到遗忘... ex;
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
Run Code Online (Sandbox Code Playgroud)
优化
如果您正在跳过maaaaaaany迭代,那么在此时ifyinglist结果将变得内存效率低下.尝试迭代消费z:
for el in z:
print(el)
if el == 4:
for _ in xrange(3): # Skip the next 3 iterations.
next(z)
Run Code Online (Sandbox Code Playgroud)
感谢@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
Run Code Online (Sandbox Code Playgroud)