gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:51:48 25 4
gpt4 key购买 nike

有时我需要对不带参数的函数使用多处理。我希望我能做类似的事情:

from multiprocessing import Pool

def f(): # no argument
return 1

# TypeError: f() takes no arguments (1 given)
print Pool(2).map(f, range(10))

我可以做 Process(target=f, args=()),但我更喜欢 map/imap/imap_unordered。有办法吗?

最佳答案

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

from multiprocessing import Pool

def f(): # no argument
return 1

print Pool(2).starmap(f, [() for _ in range(10)])

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

关于python - 我可以将 map/imap/imap_unordered 与不带参数的函数一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27689834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com