我希望能够 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()
函数。
最佳答案
将 yield
语句更改为:
yield (n,) + tuple(map(next, iterators))
或者使用izip
和enumerate
来消除整个循环:
from itertools import izip
def multi_enumerate(*iterables):
return ((n,) + t for n, t in enumerate(izip(*iterables)))
关于python - 可变长度 'yield' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13017225/