The concurrent.futures.Executor.map http://docs.python.org/py3k/library/concurrent.futures.html#concurrent.futures.Executor.map接受可变数量的可迭代对象,从中调用给定的函数。如果我有一个生成元组的生成器,并且通常会就地解压,我应该如何调用它?
以下代码不起作用,因为每个生成的元组都作为映射的不同参数给出:
args = ((a, b) for (a, b) in c)
for result in executor.map(f, *args):
pass
如果没有生成器,映射所需的参数可能如下所示:
executor.map(
f,
(i[0] for i in args),
(i[1] for i in args),
...,
(i[N] for i in args),
)
一个论点被重复,一个论点在c
from itertools import repeat
for result in executor.map(f, repeat(a), c):
pass
需要拆开以下物品的包装c
,并且可以解压c
from itertools import izip
for result in executor.map(f, *izip(*c)):
pass
需要拆开以下物品的包装c
, 无法解压c
- Change
f
接受单个参数并将该参数解包到函数中。
-
如果每个项目在c
成员数量不定,或者您正在致电f
只有几次:
executor.map(lambda args, f=f: f(*args), c)
它定义了一个新函数,用于解压其中的每个项目c
并打电话f
。使用默认参数f
in the lambda
makes f
本地内部的lambda
从而减少查找时间。
-
如果你有固定数量的参数,并且需要调用f
很多时间:
from collections import deque
def itemtee(iterable, n=2):
def gen(it = iter(iterable), items = deque(), next = next):
popleft = items.popleft
extend = items.extend
while True:
if not items:
extend(next(it))
yield popleft()
return [gen()] * n
executor.map(f, *itemtee(c, n))
Where n
是参数的数量f
。这是改编自itertools.tee http://docs.python.org/library/itertools.html#itertools.tee.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)