簡體   English   中英

Python 如何在執行程序中傳遞參數對列表。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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM