Python字典列表的多处理

2024-04-24 08:46:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典清单。 列表dict=[{'name' : 'bob', 'weight': 50}, {'name' : 'ramesh', 'weight': 60}]

我想同时处理这两本词典

这个多处理池或进程应该使用什么?你知道吗


Tags: name列表字典进程dictbobweight本词典
2条回答

我试过使用多处理池

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:list\ of\ dict的映射池.map功能。很简单!你知道吗

相关问题 更多 >