在 ThreadPoolExecutor.map() 中传递多个参数

Wel*_*lls 1 python python-3.x

以下代码:

import concurrent.futures 

def worker(item, truefalse):
    print(item, truefalse)
    return item

processed = []
with concurrent.futures.ThreadPoolExecutor() as pool:
    for res in pool.map(worker, [1,2,3], False):
        processed.append(res)
Run Code Online (Sandbox Code Playgroud)

产生异常: TypeError: zip argument #2 must support iteration

我也试过: for res in pool.map(worker, ([1,2,3], False)):

其中产生: TypeError: worker() missing 1 required positional argument: 'truefalse'

如何在调用中将多个参数传递给函数ThreadPoolExecutor.map()

Sha*_*ger 6

如果您尝试使用1, False, then 2, False, then调用辅助函数,则3, False需要将您的 single 扩展FalseFalses的迭代,至少与另一个迭代一样长。两种有效的方法:

  1. 乘以一个序列:

    for res in pool.map(worker, [1,2,3], [False] * 3):
    
    Run Code Online (Sandbox Code Playgroud)
  2. 用于itertools.repeat根据需要制作它(map当最短的迭代用完时将停止)。添加from itertools import repeat到文件顶部,然后使用:

    for res in pool.map(worker, [1,2,3], repeat(False)):
    
    Run Code Online (Sandbox Code Playgroud)

作为记录,这也是您使用常规 执行此操作的方式map,而不仅仅是ThreadPoolExecutor.