python - 如何在函数中更新全局字典

标签 python

我正在创建一个这样的程序。

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/

相关文章:

android - 如何将 python shell 转换为 android 应用程序

Python2.7 日志级别的日志记录不起作用

python - 在 Python 中布置 MVC 类

python - 当净值不为正时将两个python字典合并为一个

python - 如何对多列、不同类型、不同长度进行爆破?

python - 如何将 for 循环推进 2 次迭代?

python - 我可以使用抽象方法来导入 (Python) Pandas 数据的特定于文件的格式吗?

python - 使用外键作为参数在 Django 中过滤对象

python pip install poster 给我错误 --> 命令 "python setup.py egg_info"失败,错误代码 1 in C :\Users\

Python - 遇到 x_test y_test 拟合错误