问题
I have a dictionary that for each key there are five values in list, such as:
{"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0],
"C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
I want to sum first, second and etc. values for all keys and add it in new list such as:
[0.96, 0.19, 0.3, 1.26, 0]
I tried by below code solve it but It didn't work:
aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
bb = []
for value in (aa.items()):
for item in value:
bb.append(item)
回答1:
You can use the zip() function
aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
bb = []
for value in (zip(*list(aa.values()))):
bb.append(sum(value))
print (bb)
output :
[0.96, 0.19, 0.3, 1.26, 0]
回答2:
do you mind using numpy? if not you can use this
aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
import numpy as np
bb = np.array([aa.get(a) for a in aa])
print(np.sum(bb, axis=0))
the output will be : [ 0.96 0.19 0.3 1.26 0. ]
回答3:
You can use reduce in addition with zip to calculate sum by element wise.
from functools import reduce
a = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0],
"C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
b = reduce(lambda x, y: ([x1 + y1 for x1,y1 in zip(x,y)]), a.values())
回答4:
You can try more simple way :
>>> aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
>>> b = [sum(value) for value in zip(*aa.values())]
>>> b
[0.96, 0.19, 0.3, 1.26, 0]
>>>
回答5:
First of all, you want to use aa.values(), not aa.items(). aa.items gives tuples of (key, value), but you just want the values.
Second of all, you want to sum the items in the list, so use sum.
aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
bb = []
for value in (aa.values()):
bb.append(sum(value))
来源:https://stackoverflow.com/questions/45407538/how-to-sum-values-in-dictionary-based-on-position