Python 如何在 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、日期的每个组合作为参数

预期输出:

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)

这也不管用而且看起来很笨拙: 首先使用循环来构建参数组合列表,例如

args = [[1,a][1,b][1,c]
        [2,a],[2,b],[2,c]
        ...
       ]

并将其传递给 f:

    executor.map(f, args)

    executor.map(f, *args) 

失败

或者重新设计 f 使其只接受一个参数?

必须有一个好方法...

.map() 将并行迭代所有可迭代对象。它不会尝试查找所有组合:

If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.

一个简单的修复方法是使用 itertools.product。我能想到没有比 更好的可读方式了:

将您的函数更改为:

def f(t):
  id, date = t
  print(f'{id} - {date}')

然后:

import itertools
...
    executor.map(f, itertools.product(ids, dates))