3

我希望能够yield使用可变数量的项目,这将允许编写类似于以下内容的生成器函数:

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

def multi_enumerate(*iterables):
    n = 0
    iterators = map(iter, iterables)
    while iterators:
        yield n, *tuple(map(next, iterators))  # invalid syntax
        n += 1

for i,a,b,c in multi_enumerate(x, y, z):
    print i,a,b,c

任何人都知道一些方法来做到这一点?我知道我可以产生一个元组,但这需要在接收端明确解包它,例如a,b,c = t[0], t[1], t[2]

最终解决方案

FWIW,这是我最终使用的,基于 John Kugelman 的出色回答:

from itertools import izip

def multi_enumerate(*iterables, **kwds):
    start = kwds.get('start')
    if start is None:
        if kwds: raise TypeError(
            "multi_enumerate() accepts only the keyword argument 'start'")
        try:
            iter(iterables[-1])  # last non-keyword arg something iterable?
        except TypeError:        # no, assume it's the start value
            start, iterables = iterables[-1], iterables[:-1]
        else:
            start = 0  # default

    return ((n,)+t for n, t in enumerate(izip(*iterables), start))

添加的代码是因为我希望它也接受一个可选的不可迭代的最后一个参数来指定 0 以外的起始值(或使用start关键字参数指定它),就像内置enumerate()函数一样。

4

4 回答 4

5

yield将语句更改为:

yield (n,) + tuple(map(next, iterators))

或者使用izipandenumerate来消除整个循环:

from itertools import izip

def multi_enumerate(*iterables):
    return ((n,) + t for n, t in enumerate(izip(*iterables)))
于 2012-10-22T18:18:00.193 回答
1

I would use chain from itertools:

yield tuple(chain((n,), map(next, iterators)))
于 2012-10-22T18:20:29.257 回答
0

This will return an iterator that produces (n, *l[n]) for i n-length ls. It will work directly in place of your multienumerate method.

from itertools import izip
def enumerated_columns(*rows):
    return izip(range(len(rows[0])), *rows)
于 2012-10-22T18:20:43.347 回答
0

If you want to delegate several items from your generator to some other generator, there's no one-line way to do this — unless you use Python 3.3 that features yield from.

I'd iterate over the nested generators yielding values from them explicitly, something like

yield n
for value in (delegated.next for delegated in iterators):
  yield value
于 2012-10-22T18:22:47.353 回答