循环跳过多个迭代

时间:2018-12-05 12:00:09

标签: python algorithm python-2.7 list iteration

寻找可以跳过多个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

Python 2中有这种东西吗?

2 个答案:

答案 0 :(得分:5)

我要遍历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 迭代,那么此时list的修改结果将导致内存效率低下。尝试迭代使用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

答案 1 :(得分:3)

为此,您可以使用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
相关问题