是否有类似于pools.starmap的函数可以用于字典列表?
与其说:
pools.starmap(func, iterable_of_tuple)
你需要:
pools.starmapdict(func, iterable_of_dictionaries)
这样,starmapdict函数就负责拆开函数参数的字典。
是否有类似于pools.starmap的函数可以用于字典列表?
与其说:
pools.starmap(func, iterable_of_tuple)
你需要:
pools.starmapdict(func, iterable_of_dictionaries)
这样,starmapdict函数就负责拆开函数参数的字典。
from multiprocessing import Pool
data = [{"name": "Delphi", "age": 13}, {"name": "Orion", "age":24}, {"name": "Asher"}, {"name": "Baccus"}]
def fun_wrapper(dict_args):
return fun(**dict_args)
def fun(name="Iseult", age=30):
print(name, age)
if __name__ == '__main__':
with Pool(3) as pool:
pool.map(fun_wrapper, data)
fun_wrapper函数负责解包字典并将其传递给fun函数。
这是一个有点老的问题,但我有答案:
不要使用StarMap;使用Map。假设,
pool.starmap(func, list_of_dictionaries)
改为:
pool.map(func, list_of_dictionaries)
从文档中,
map()和starmap()之间的区别类似于function(a,b)和function(*c)之间的区别。
因此,使用包含字典列表的starmap将解压缩字典键作为参数;这根本不是你想要的。
from multiprocessing import Pool
data = [
{"name": "Delphi"}, {"name": "Orion"}, {"name": "Asher"}, {"name": "Baccus"}
]
def fun(*args):
print(args)
with Pool(4) as pool:
pool.starmap(fun,data)
#Prints: """
$> name
$> name
$> name
$> name
"""
from multiprocessing import Pool
data = [
{"name": "Delphi"}, {"name": "Orion"}, {"name": "Asher"}, {"name": "Baccus"}
]
def fun(object):
print(object)
with Pool(4) as pool:
pool.map(fun,data)
#Prints: """
$> {"name": "Delphi"}
$> {"name": "Orion"}
$> {"name": "Asher"}
$> {"name": "Baccus"}
"""
pools.starmap(func, zip(iterable_of_dictionaries.keys(), iterable_of_dictionaries.values())
编辑1:
>>> d = {"a": "1", "b": "2"}
>>> print(d.items())
dict_items([('a', '1'), ('b', '2')])
>>> print(d.keys(), d.values())
dict_keys(['a', 'b']) dict_values(['1', '2'])
zip(d.keys(), d.values())
不就等同于 d.items()
吗? - monkut