Multiprocessing 将itertools与map结合使用

Multiprocessing 将itertools与map结合使用,multiprocessing,itertools,Multiprocessing,Itertools,我正在寻找一种“成熟的”pythonic方法,将itertools与map函数结合使用,希望能用于多处理。我将试着用一个例子来说明。我将使用python的map函数,因为它比多处理中的map函数更简单 假设你有一个函数,它有两个参数 def twoparameterfunction(x,y): return somethingnice(x,y) xs, ys = zip(*[pairs for pairs in itertools.combinations([1,2,3,4,5],2

我正在寻找一种“成熟的”pythonic方法,将itertools与map函数结合使用,希望能用于多处理。我将试着用一个例子来说明。我将使用python的map函数,因为它比多处理中的map函数更简单

假设你有一个函数,它有两个参数

def twoparameterfunction(x,y):
    return somethingnice(x,y)


xs, ys = zip(*[pairs for pairs in itertools.combinations([1,2,3,4,5],2)])

results = map(twoparameterfunction,xs,ys)
是让map将函数应用于itertools.combines生成的对的一种方法。本质上,我首先从一对对列表中创建一对列表,然后将该对列表用于map函数

这不可能是这样做的!我希望有人能给我一个更好的方法

附言:如果这是显而易见的,你觉得有必要否决这篇文章,请也提供一个显而易见的答案。谢谢。

为非并发情况提供了解决方案:

from itertools import starmap

results = list(starmap(twoparameterfunction,
                       itertools.combinations([1, 2, 3, 4, 5], 2)))
对于多处理映射,不能使用星图。(您也不能使用多个输入iterables,因此也不能使用zip转置解决方案。)在这种情况下,最好定义一个接受元组并将元素传递给
twoparameterfunction

def starfunc(x_y):
    return twoparameterfunction(*x_y)

results = some_appropriate_pool.map(
        starfunc, itertools.combinations([1, 2, 3, 4, 5], 2))

如果所讨论的twoparameterfunction是一个类的方法,并且必须被称为:Object.twoparameterfunction(x,y)@tipanverella:Yes,那么是否也建议使用帮助函数方法。如果它是一个实例方法,您可能需要一个闭包或
functools.partial
。我将研究functools.partial。