2017-08-23 19 views
1

私はこのようなプログラムを作成しています。関数内のグローバル辞書を更新するには

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を変更し、(ファイルに書き込む)を印刷するために、main関数に更新されたグローバル変数を返すようにしたいです。しかし、それ以前は、エラーTypeError: 'int' object is unsubscriptableが発生しています。これをどのように機能させることができますか?

私はキーワードglobalを使用してグローバル変数を変更する方法についていくつかの質問を読んで、しかしfun1()global dict2を配置する変数を毎回リセットされます。

更新:

がどのように私はmultiprocessing.Poolとしてdct[0]ようdctを処理することが可能で反復可能なのチャンクを送信するループのように行動するだろうか?

+0

multiprocessing'私はコードが同じグローバル変数へのアクセスを持っているとは思いません。 – quamrana

+0

'i'はどこにでも定義/初期化する必要はありません。 – tdube

答えて

1

最終バージョンの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} 
関連する問題