我可以将map / imap / imap_unordered与不带参数的函数一起使用吗?

usu*_* me 8 python python-multiprocessing

有时我需要使用没有参数的函数的多重处理。我希望我可以做类似的事情:

from multiprocessing import Pool

def f():  # no argument
    return 1

# TypeError: f() takes no arguments (1 given)
print Pool(2).map(f, range(10))
Run Code Online (Sandbox Code Playgroud)

我可以做Process(target=f, args=()),但我更喜欢的语法map/ imap/ imap_unordered。有没有办法做到这一点?

Lea*_*ile 9

您可以使用pool.starmap()而不是.map()这样:

from multiprocessing import Pool

def f():  # no argument
    return 1

print Pool(2).starmap(f, [() for _ in range(10)])
Run Code Online (Sandbox Code Playgroud)

starmap将给定可迭代对象的所有元素作为参数传递给f. 在你的情况下,迭代应该是空的。


the*_*eye 7

map函数的第一个参数应该是一个函数,并且应该接受一个参数。这是强制性的,因为将迭代作为第二个参数传递的iterable,并且在每次迭代中将值一一传递给函数。

因此,最好的选择是重新定义f以接受一个参数并忽略它,或者编写带有一个参数的包装器函数,忽略该参数并返回的返回值f,例如

from multiprocessing import Pool

def f():  # no argument
    return 1

def throw_away_function(_):
    return f()

print(Pool(2).map(throw_away_function, range(10)))
# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Run Code Online (Sandbox Code Playgroud)

您不能将lamdba功能与池一起使用,因为它们不可腌制。