循环中跳过多个迭代

4

寻找一种方法,可以跳过多个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个回答

6

我会使用islice来迭代iter(z),将不需要的元素删除...例如:

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

优化
如果您跳过了很多次迭代,那么在那时将结果转换为列表将变得不够高效。尝试迭代消耗z

for el in z:
    print(el)
    if el == 4:
        for _ in xrange(3):  # Skip the next 3 iterations.
            next(z)

感谢@Netwave的建议。


如果您还想要索引,请考虑在enumerate(z)调用中包装iter(对于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
生成一个“垃圾”列表似乎不是最好的选择。也许可以用一个简单的循环来消耗它?for _ in xrange(3): next(z),顺便说一下,不需要使用iter,因为islice已经像一个迭代器一样行事了。 - Netwave
1
我喜欢这个答案,但是想要颠倒顺序。先是 next,然后是 list(islice(...)) 作为一种教育性的替代方案。 - jpp

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

1
这实际上并不跳过循环迭代。 - cs95
好的,看起来不错。顺便说一下,我没有给你点踩,但我希望那个点踩的人能看到这个并取消它。 - cs95
1
嗯,还有一个建议,你可能会因为疏忽而跳过一个额外的迭代,所以再看一下吧。 - cs95

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接