我正在努力理解下面的代码是如何工作的。它来自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
目前没有回答
相关问题 更多 >
编程相关推荐