我有两个清单:
a = [1, 2, 3, 4]
b = [9, 8, 7, 6]
我希望将这两个列表的每个组合作为参数传递给函数I'多线程:
def test(hello, world):
return hello + world
with ThreadPoolExecutor(max_workers=10) as executor:
future_to_stuff = { executor.submit(self._http_check_port, hello, world): ### }
for future in as_completed(future_to_port):
...
我试图找出如何解开"解包"我的两个列表都将a
和b
中的每个值组合作为参数发送给函数。
答案 0 :(得分:2)
我通常使用以下列表理解。
future_to_stuff = [executor.submit(test, hello, world)
for hello, world in zip(a, b)]
这是修改后的代码。
from concurrent.futures import ThreadPoolExecutor, as_completed
def test(hello, world):
return hello + world
def main(a, b):
with ThreadPoolExecutor(max_workers=10) as executor:
future_to_stuff = [executor.submit(test, hello, world)
for hello, world in zip(a, b)]
for future in as_completed(future_to_stuff):
print(future.result())
if __name__ == '__main__':
a = [1, 2, 3, 4]
b = [9, 8, 7, 6]
main(a, b)
另一种方法是使用.map
方法而不是.submit
。
from concurrent.futures import ThreadPoolExecutor, as_completed
def test(hello, world):
return hello + world
def main(a, b):
with ThreadPoolExecutor(max_workers=10) as executor:
results = executor.map(test, a, b)
for result in results:
print(result)
if __name__ == '__main__':
a = [1, 2, 3, 4]
b = [9, 8, 7, 6]
main(a, b)