我很努力地理解下面的代碼是如何工作的。它來自http://docs.python.org/library/itertools.html#itertools.izip_longest,是izip_longest迭代器的純python等價物。我對哨兵功能特別迷惑,它是如何工作的?itertools中的izip_longest:這裏發生了什麼?
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
另外,'sentinel()'可以被調用無限次而不會引發任何異常。 – 2011-03-14 13:10:11
@Sven:你說的對,我解決了。 – 2011-03-14 13:31:23