Изначально у меня есть структура данных, такая как 'motif':
мотив = { '1S-2C,2C-2C' :[ [[1,2],[2,2]], [[3,5],[5,5]], [ [4,6],[6,6]] ],'1S-1S,1S-2C': [[[1,1],[1,2]], [[3,3],[3,5 ]] ]}*
Я хотел бы создать подпроцесс для каждого ключа и передать его в некоторую функцию с именем 'extension()'. Обновление каждого элемента выполняется в 'modify()'.
Проблема с приведенным ниже фрагментом: я получаю вывод, подобный этому 'returnMotif': {'1S-2C,2C-2C,3E-3E':[[[1, 2], [2 , 2], [0, 0]], [[3, 5], [5, 5], [0, 0]], [[4, 6], [6, 6], [0, 0]] ],'1S-1S,1S-2C,3O-3O': [[[1,1],[1,2],[0,0]], [[3,3],[3,5], [0,0]] ]} .т.е. они точно падают туда же откуда звонили не глядя на клавиши. Но я хочу, чтобы «returnMotif» выглядел так:
returnMotif = { '1S-2C,2C-2C,3E-3E' : [[[1,2],[2,2],[0,0]], [[4,6 ],[6,6],[0,0]] ], '1S-1S,2C-2C,3O-3O' : [[[3,5],[5,5],[0,0]] ], '1S-1S,1S-2C,3E-3E' : [[[1,1],[1,2],[0,0]]], '1S-1S,1S-2C,3O-3O ' : [ [[3,3],[3,5],[0,0]] ]} Итак, как я могу перебрать словарь 'motif' с помощью многопроцессорного модуля и получить все обновленные элементы в 'returnMotif' в main()?
У меня есть такой патч: Может ли кто-нибудь внести какие-либо изменения по этому поводу?
from multiprocessing import Pool,Manager
from collections import defaultdict
def modify(x,i):
#print i[1][1]
if i[1][1] % 2 == 0:
return x+',3E-3E' #last element is even
else:
return x+',3O-3O'# last element is odd
def extension(x): # Function that is called during multiprocessing.
# do some function on each element like [[1,2],[2,2]],[[3,5],5,5]], [[1,1],[1,2]], [[3,3],[3,5]], [[4,6],[6,6]]. Let it be the function 'modify()'
#print x # should have the key
#print motif[x] # clearly has the value
allTemps=[]
for i in motif[x]:
#print i
(newX) = modify(x, i)
i.append([0,0])
allTemps.append(i)
return (newX,allTemps)
if __name__ == "__main__":
# Dictionary with list of list of parameters:
motif={'1S-2C,2C-2C':[ [[1,2],[2,2]], [[3,5],[5,5]], [[4,6],[6,6]] ]}
p = Pool(4) # Setting up the number of CPU's to use.
returnMotif = dict( p.map( extension , motif.keys() ) )
p.close()
p.join()
# when I return the modified keys and values, they exactly fall in the same place from where they called without looking at the keys ie, [[1,2],[2,2]], [[3,5],[5,5]], [[4,6],[6,6]] these 3 elements have the same key '1S-2C,2C-2C'. But in the modified key-value pairs, only two of them have same key and the third one is having a different key. ie, [[1,2],[2,2],[0,0]] , [[4,6],[6,6],[0,0]] these two elements have a key of '1S-2C,2C-2C,3E-3E' and [[3,5],[5,5],[0,0]] has a key of '1S-2C,2C-2C,3O-3O'. But it's coming like this: ** returnMotif ** 1S-2C,2C-2C,3E-3E [[[1, 2], [2, 2], [0, 0]], [[3, 5], [5, 5], [0, 0]], [[4, 6], [6, 6], [0, 0]]]
#I want it to be split into two key-value pair like format below :{'1S-2C,2C-2C,3E-3E':[[[1, 2], [2, 2], [0, 0]], [[4, 6], [6, 6], [0, 0]]] ,'1S-2C,2C-2C,3O-3O':[ [[3, 5], [5, 5], [0, 0]] ]}
print "** Return Motifs:\n"
for i in returnMotif:
print i,"\t",returnMotif[i],"\n"