[英]How to correctly pass the generator to the function parameters of ThreadPoolExecutor Executor.map()?
[英]Python how to pass list of argument pair in executor.map
我有的:
ids = [1,2,3...]
dates = ['a', 'b', 'c'...]
def f(id, date):
print(f'{id} - {date}')
我打算做什么:在多线程中运行 f,每个 id 组合,日期为 arguments
预期 output:
1 - a
1 - b
1 - c
2 - a
2 - b
2 - c
3 - a
3 - b
3 - c
...
这显然行不通
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
executor.map(f, ids, dates)
这也不起作用并且看起来很笨拙:首先使用循环来构建 arguments 组合列表,例如
args = [[1,a][1,b][1,c]
[2,a],[2,b],[2,c]
...
]
并将其传递给 f:
executor.map(f, args)
或者
executor.map(f, *args)
要么失败
或者重新设计 f 使其只需要一个参数?
一定有个好办法...
.map()
将并行迭代所有可迭代对象。 它不会尝试查找所有组合:
如果通过了额外的可迭代 arguments,则 function 必须采用那么多 arguments 并并行应用于所有可迭代的项目。
一个简单的解决方法是使用itertools.product
。 我想不出更好更易读的方法:
将您的 function 更改为:
def f(t):
id, date = t
print(f'{id} - {date}')
然后:
import itertools
...
executor.map(f, itertools.product(ids, dates))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.