我正在创建一个这样的程序。
from __future__ import print_function
import multiprocessing
dict1 = dict( (k,v) for (k,v) in zip(range(0,11),range(50,61)))
dict2={}
dict3={}
def fun1(dct):
#How can I process `dct` as `multiprocessing.Pool` would act like a loop sending chunks of iterable?
#I can do:
# for i in dct:
# dict2.update({dct[i]:i})
# but `multiprocessing.Pool` will do the looping part automatically. In this case what should be done to index `dct`?
#dict2.update({dct[i]:i})
return dict2
if __name__ == '__main__':
p=multiprocessing.Pool(2)
dict3=p.map(fun1,dict1)
p.close()
p.join()
print(dict3) #write in file
我想修改函数fun1
内的全局变量dict2
并将更新后的全局变量返回到主函数进行打印(将其写入文件)。但是,在此之前,我收到错误 TypeError: 'int' object is unsubscriptable
。我怎样才能让它发挥作用?
我读到了一些关于如何使用关键字 global
修改全局变量的问题,但是将 global dict2
放入 fun1()
将重置每次都有变化。
更新:
如何像 dct[0]
一样处理 dct
,因为 multiprocessing.Pool
会像循环发送可迭代 block 一样?
最佳答案
这将为您提供 dict2
的最终版本,但我不确定 multiprocessing
是否会在性能方面为您带来任何好处。
警告:Python3 警报
import multiprocessing
dict1 = dict( (k,v) for (k,v) in zip(range(0,11),range(50,61)))
dict2={}
def fun1(dct):
key, value, dict2 = dct #unpack tuple
# This code would not update dict2
# dict2.update({value:key})
# return the value and key reversed. I assume this is what you are after.
return {value:key}
if __name__ == '__main__':
p=multiprocessing.Pool(2)
# pass the tuple of (key,value,dict2) into each call of fun1
dict3=p.map(fun1,((key,value,dict2) for key, value in dict1.items()))
p.close()
p.join()
print(dict1) # original dict
print(dict2) # remains empty
print(dict3) # this is a list of the results
for d in dict3:
dict2.update(d)
# Now dict2 is populated
print(dict2)
输出:
{0: 50, 1: 51, 2: 52, 3: 53, 4: 54, 5: 55, 6: 56, 7: 57, 8: 58, 9: 59, 10: 60}
{}
[{50: 0}, {51: 1}, {52: 2}, {53: 3}, {54: 4}, {55: 5}, {56: 6}, {57: 7}, {58: 8}, {59: 9}, {60: 10}]
{50: 0, 51: 1, 52: 2, 53: 3, 54: 4, 55: 5, 56: 6, 57: 7, 58: 8, 59: 9, 60: 10}
关于python - 如何在函数中更新全局字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45840915/