Python使用多个输入对函数进行多处理 [英] Python multiprocessing a function with several inputs

查看:173
本文介绍了Python使用多个输入对函数进行多处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,multiprocessing模块可用于在一系列值范围内并行运行函数.例如,这将生成f的前100000个评估的列表.

In Python the multiprocessing module can be used to run a function over a range of values in parallel. For example, this produces a list of the first 100000 evaluations of f.

def f(i):
    return i * i

def main():
    import multiprocessing
    pool = multiprocessing.Pool(2)
    ans = pool.map(f, range(100000))

    return ans

当f接受多个输入但仅改变一个变量时,是否可以执行类似的操作?例如,您将如何并行处理此问题:

Can a similar thing be done when f takes multiple inputs but only one variable is varied? For example, how would you parallelize this:

def f(i, n):
    return i * i + 2*n

def main():
    ans = []
    for i in range(100000):
        ans.append(f(i, 20))

    return ans

推荐答案

有几种方法可以做到这一点.在问题给出的示例中,您只需定义一个包装器函数

There are several ways to do this. In the example given in the question, you could just define a wrapper function

def g(i):
    return f(i, 20)

,然后将此包装传递给map().一种更通用的方法是使用一个包装器,该包装器使用一个元组参数并将该元组解包为多个参数

and pass this wrapper to map(). A more general approach is to have a wrapper that takes a single tuple argument and unpacks the tuple to multiple arguments

def g(tup):
    return f(*tup)

或使用等效的lambda表达式:lambda tup: f(*tup).

or use a equivalent lambda expression: lambda tup: f(*tup).

这篇关于Python使用多个输入对函数进行多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆