如何根据位置对字典中的值求和? [英] How to sum values in dictionary based on position?
本文介绍了如何根据位置对字典中的值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典,其中每个键在列表中都有五个值,例如:
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)
推荐答案
您可以使用zip()
函数
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)
输出:
[0.96, 0.19, 0.3, 1.26, 0]
这篇关于如何根据位置对字典中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文