我有一个字典列表。 list_of_dict =[{'name' : 'bob', 'weight': 50}, {'name' : 'ramesh', 'weight': 60}]
我想同时处理两个词典
我应该为此多处理池或进程使用什么?
我尝试过使用多处理池
from multiprocessing.pool import ThreadPool as Pool
pool_size = 5
def worker(item1, itme2):
try:
print(item1.get('weight'))
print(itme2)
except:
print('error with item')
pool = Pool(pool_size)
items = [{'name' : 'bob', 'weight': 50}, {'name' : 'ramesh','weight': 60}]
for item in items:
pool.apply_async(worker, (item, 'item2'))
pool.close()
pool.join()
我使用以下内容,因为它简单易懂:
from multiprocessing.dummy import Pool as ThreadPool
def threadfunction(dict):
weight = dict.get('weight')
return weight
pool = ThreadPool(5)
threadresults = pool.map(threadfunction,list_of_dict)
pool.close()
pool.join()
它将处理列表的映射:list_of_dict。 所以你只需要将线程数传递给 ThreadPool(( 函数,并将函数和列表传递给 pool.map 函数。 简单!