具有可迭代和多个参数的Python多处理

亨利·桑顿

使用多重处理,我想传递一个可迭代的多个参数:

a)运行在n_core cpu上的函数b)一次产生(或返回)n_core结果c)以任何完成顺序

from multiprocessing import Pool 

def func(iterable, args):
    this, that, other = args[0], args[1], args[2]

    for s in iterable:
        return ' '.join([s, this, that, other])        

def main():
    iterable = ['abc', 'bcd', 'cde', 'def', 'efg', 'fgh', 'ghi', 'hij']
    args = ['this', 'that', 'other']
    n_core = 2

    p = Pool(n_core)
    for r in p.imap_unordered(func, iterable, args):
        print(r)

if __name__ == '__main__':
    main()

预期结果是:

"abc this that other"
"bcd this that other"
"cde this that other"
"def this that other" 
"efg this that other" 
"fgh this that other"
"ghi this that other" 
"hij this that other"

使这项工作正确的方法是什么?

其次,并发.futures.ProcessPoolExecutor是否可以解决此问题?

大卫·卡伦

您可以创建一个new_iterable将的值iterable结合在一起的args

from multiprocessing import Pool

def func(args):
    iterable, this, that, other = args[0], args[1][0], args[1][1], args[1][2]
    return ' '.join([iterable, this, that, other])

def main():
    iterable = ['abc', 'bcd', 'cde', 'def', 'efg', 'fgh', 'ghi', 'hij']
    args = ['this', 'that', 'other']
    new_iterable = ([x, args] for x in iterable)
    n_core = 2

    p = Pool(n_core)
    for r in p.imap_unordered(func, new_iterable):
        print(r)

if __name__ == '__main__':
    main()

输出量

abc this that other
bcd this that other
cde this that other
def this that other
efg this that other
fgh this that other
ghi this that other
hij this that other

该解决方案使用生成器表达式来创建新的可迭代项iterable,该可迭代项将来自的条目与所需的合并args您还可以使用生成器函数执行相同的操作。

更新:我进行了修改,func以产生您在评论中提到并添加到您的问题的预期结果。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

具有多处理功能的Python itertools-庞大的列表与使用迭代器的低CPU使用率

使用python多处理程序以具有不同参数组合的循环运行脚本

如何提示python3.6该参数必须同时具有大小和可迭代性?

具有多个tqdm进度条的多处理

如何在单个可迭代的python上同时具有多个迭代器?

具有共享队列和结束条件的多处理

具有多处理pathos库的简单python程序

如何为具有6个不同类型和大小的参数的函数实现多处理

如何使用具有多个agruments的函数运行多处理python请求

多个可迭代项作为python多重处理中的参数

具有在python中需要多个参数的方法的多处理池

具有多个输入参数但只有一个可迭代的函数中的python多处理池

具有进程池和自定义管理器的Python多处理事件

具有多个参数和void函数的Python多处理池

Python中具有多个(关键字)参数的多处理

Python-具有两个参数的多处理StarMap

Python-具有多个for循环的多处理

具有类/返回列表的多处理-Python

需要Python多处理和参数传递帮助

可迭代的多处理队列未退出

具有多个参数的Python多处理池映射

具有数组和多个参数的Python多处理

在python中对具有多个参数的函数进行多处理

具有子进程标志的Python多处理无法运行

处理器和迭代的 Python 多处理比率

具有异步函数的 Python 多处理

多重处理具有可迭代和可迭代参数的函数

Python 多处理 - 参数的“外积”

python多处理映射中的PID是否保证相对于可迭代具有递增顺序?