python函数传多个参数_多重处理-在Python中将多个参数传递给pool.map()函数

您可以使用允许多个参数的map函数,就像dill中的pathos的fork一样。

>>> from pathos.multiprocessing import ProcessingPool as Pool

>>>

>>> def add_and_subtract(x,y):

... return x+y, x-y

...

>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))

>>> res

[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]

>>> Pool().map(add_and_subtract, *zip(*res))

[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos使您可以轻松地嵌套具有多个输入的层次结构并行映射,因此我们可以扩展示例来演示这一点。

>>> from pathos.multiprocessing import ThreadingPool as TPool

>>>

>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))

>>> res.get()

[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

更有趣的是,构建一个可以传递到Pool中的嵌套函数。这是可能的,因为pathos使用dill,可以在python中序列化几乎所有内容。

>>> def build_fun_things(f, g):

... def do_fun_things(x, y):

... return f(x,y), g(x,y)

... return do_fun_things

...

>>> def add(x,y):

... return x+y

...

>>> def sub(x,y):

... return x-y

...

>>> neato = build_fun_things(add, sub)

>>>

>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))

>>> list(res)

[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

但是,如果您不能超出标准库的范围,则必须采用另一种方法。 在这种情况下,最好的选择是使用pathos,如下所示:Python multiprocessing pool.map用于多个参数(在OP帖子的评论中由@Roberto指出)

在这里获取pathos:[https://github.com/uqfoundation]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值