伊兹普:这是怎么回事?

2024-05-19 11:31:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力理解下面的代码是如何工作的。它来自http://docs.python.org/library/itertools.html#itertools.izip_longest,是纯python等价于izip最长迭代器。我对哨兵功能特别迷惑不解,它是如何工作的?

def izip_longest(*args, **kwds):
    # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
    fillvalue = kwds.get('fillvalue')
    def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
        yield counter()         # yields the fillvalue, or raises IndexError
    fillers = repeat(fillvalue)
    iters = [chain(it, sentinel(), fillers) for it in args]
    try:
        for tup in izip(*iters):
            yield tup
    except IndexError:
        pass

Tags: forlongestdefcounterargsitsentinelitertools

热门问题