【问题标题】:Python how to pass list of argument pair in executor.mapPython如何在executor.map中传递参数对列表
【发布时间】:2020-11-09 06:26:17
【问题描述】:

我有什么:

ids = [1,2,3...]
dates = ['a', 'b', 'c'...]

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

我打算做什么: 在多线程中使用 id、日期作为参数的每个组合运行 f

预期输出:

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 使其只需要一个参数?

一定有个好办法……

【问题讨论】:

    标签: python python-3.x multithreading arguments


    【解决方案1】:

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

    如果传递了额外的可迭代参数,则函数必须接受那么多参数并并行应用于所有可迭代的项目。

    一个简单的解决方法是使用itertools.product。我想不出更好的可读方式:

    将您的功能更改为:

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

    然后:

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

    【讨论】:

    • 只是意识到我的问题实际上是如何在 map() 中传递多个参数,经过一些研究我发现另一个解决方案可能是 functools.partial。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2010-10-15
    • 2018-09-21
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多