【问题标题】:PEP 479, map() and StopIterationPEP 479,map() 和 StopIteration
【发布时间】:2016-07-04 23:32:35
【问题描述】:

看来PEP 479(生成器内部的更改停止迭代处理)带来了许多不便。 zip 等价物的示例代码(来自 python 的 2.7 文档,我自己略有改动):

def izip(*iterables):
   # izip('ABCD', 'xy') --> Ax By
   iterators = list(map(iter, iterables))
   while True: 
       yield tuple(map(next,iterators))

zipper = izip([1, 2], [3, 4])

下一个(拉链)

(1, 3)

下一个(拉链)

(2, 4)

下一个(拉链)

()

下一个(拉链)

()

map() 内置生成器会吞下由 next() 引发的 StopIteration,因此拉链生成器永远不会结束。我什至无法在 izip 中捕获异常,因为问题存在于 map() 本身。有没有什么 Pythonic 方法可以在不编写自定义 map() 的情况下解决这个问题?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    在这种情况下,您可以检查您要转到yieldtuple 的长度,并在它小于iterators 的长度时中断循环:

    def izip(*iterables):
        iterators = list(map(iter, iterables))
        while True:
            t = tuple(map(next,iterators))
            if len(t) != len(iterators):
                break
            yield t
    
    zipper = izip([1, 2], [3, 4])
    print(next(zipper)) # (1, 2)
    print(next(zipper)) # (3, 4)
    print(next(zipper)) # StopIteration
    

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 2018-08-14
      • 2018-10-14
      • 2018-10-06
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 2014-02-13
      • 2018-03-26
      相关资源
      最近更新 更多