【问题标题】:Skip multiple iterations in a loop在循环中跳过多次迭代
【发布时间】:2019-05-06 23:52:46
【问题描述】:

正在寻找可以跳过多个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 中有这样的东西吗?

【问题讨论】:

    标签: python algorithm python-2.7 list iteration


    【解决方案1】:

    我会遍历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
    

    【讨论】:

    • 生成“垃圾”列表看起来并不是我认为的最佳选择。也许用一个简单的循环来消耗它? for _ in xrange(3): next(z),顺便说一句,不需要使用iter,因为islice 的行为已经像一个迭代器
    • 我喜欢这个答案,但会颠倒顺序。 next 首先,list(islice(...)) 作为教育选择。
    【解决方案2】:

    您可以为此使用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
    

    【讨论】:

    • 这实际上并没有跳过循环迭代。
    • 好吧,看起来不错。顺便说一句,我没有对你投反对票,但我希望投反对票的人看到这一点并扭转它。
    • 嗯,还有一个建议,你可能会错误地跳过一个额外的迭代,所以再看一遍。
    猜你喜欢
    • 2014-10-30
    • 2019-05-23
    • 2015-02-07
    • 1970-01-01
    • 2013-07-24
    • 2021-11-15
    • 2019-05-17
    相关资源
    最近更新 更多