简体   繁体   English

如何为具有签名 f(str, str, str, list) 的函数正确使用 Python 多处理?

[英]How to correctly use Python multiprocessing for a function with signature f(str, str, str, list)?

Given the following code:鉴于以下代码:

ids = [[1,2,3], [4,5], [6,7,8,9]]
it = [('a','b', 'c', ids[i]) for i in range(len(ids))]
# [('a', 'b', 'c', [1, 2, 3]), ('a', 'b', 'c', [4, 5]), ('a', 'b', 'c', [6, 7, 8, 9])]
p = multiprocessing.Pool(2)
j = p.starmap(f, it)
p.close()
p.join()

and function of form f(str, str, str, list)和形式f(str, str, str, list) 的函数

Is this an approach with the least overhead?这是一种开销最少的方法吗? (time and space?) (时间和空间?)

'a', 'b' and 'c' come from configuration 'a'、'b' 和 'c' 来自配置

Since the first 3 arguments are always the same, you might do a bit better with:由于前 3 个参数始终相同,您可能会做得更好:

from functools import partial
import multiprocessing

ids = [[1,2,3], [4,5], [6,7,8,9]]
p = multiprocessing.Pool(2)
results = p.map(partial(f, 'a', 'b', 'c'), ids)

This saves having to create the it list.这省去了创建it列表的麻烦。 It is certainly neater.它当然更整洁。 At any rate, it would have been more Pythonic to create it as:无论如何,将it创建为更Pythonic:

it = [('a', 'b', 'c', id) for id in ids]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM