gpt4 book ai didi

python - 使用多处理附加值时获取空列表

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:53 24 4
gpt4 key购买 nike

我正在使用 Python 3.5 编辑一个列表,在本例中为 predictions_dict['D'],包含在字典 predictions_dict 中。这是我使用的代码:

import multiprocessing as multip

predictions_dict = {'A': [],
'B': [],
'C': [],
'D': [],
'E': [],
'F': [],
'Def': []}

data = [{'index': 1, 'rank': 'A'}, {'index': 2, 'rank': 'D'}, {'index': 3, 'rank': 'E'}]
prediction = [(1, 'C'), (2, 'D'), (3, 'D')]


def create_predictions_dict(index, rank):
for j in data:
if j['index'] == index:
predictions_dict[rank].append((index, j['rank'], rank))
break

np = multip.cpu_count()
p = multip.Pool(processes=np)
_ = p.starmap(create_predictions_dict, prediction)
p.close()
p.join()

print('final list:', predictions_dict['D'])

当我执行此代码时,得到的输出是:

final list: []

我不明白为什么,正如我所期望的:

final list: [(2, 'D', 'D'), (3, 'E', 'D')]

最佳答案

由于在评论中问题被确定为进程不共享状态这一事实,我已经研究了一个解决方案:

import multiprocessing as multip

predictions_dict = {'A': [],
'B': [],
'C': [],
'D': [],
'E': [],
'F': [],
'Def': []}

data = [{'index': 1, 'rank': 'A'}, {'index': 2, 'rank': 'D'}, {'index': 3, 'rank': 'E'}]
prediction = [(1, 'C'), (2, 'D'), (3, 'D')]


def create_predictions_dict(index, rank):
for j in data:
if j['index'] == index:
return index, j['rank'], rank

np = multip.cpu_count()
p = multip.Pool(processes=np)
sk = p.starmap(create_predictions_dict, prediction)
p.close()
p.join()

for elem in sk:
predictions_dict[elem[2]].append(elem)

print('final list:', predictions_dict['D'])

关于python - 使用多处理附加值时获取空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47500535/

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