[英]How would I get past this assertion test in Python for trying to find the sum of all the number of views listed in a Dictionary?
[英]how to get the sum of python dictionary listed as a tuple?
我将 python 字典列为元组,如下所示; 这里每个元组的第一个值描述了组号,每个字典描述了与组内每个数字相关的生成值,(即 {'1': 0,'3': 1,'2': 1, '5':2,'303':3}。
[('1',{'1': 0,'3': 1,'2': 1,'5': 2,'303': 3}), ('2',{'4': 0,'5': 1,'7': 1,'5': 2,'303': 2}), ('3',{'1': 0,'3': 0,'2': 0,'5': 2,'303': 3})]
有没有什么方法可以通过获取每组的总和来获取每组的总和,(即,
[('1', 7), ('2', 6), ('3', 5)]
我试图遍历每个值并获得总和,但该方法非常昂贵。
一个简单的列表理解应该如此
>>> [(k, sum(dic.values())) for k, dic in tuples]
lst = [ ("1", {"1": 0, "3": 1, "2": 1, "5": 2, "303": 3}), ("2", {"4": 0, "3": 1, "7": 1, "5": 2, "303": 2}), ("3", {"1": 0, "3": 0, "2": 0, "5": 2, "303": 3}), ] sum_of_each_group = [(i, sum(d.values())) for (i, d) in lst] print(sum_of_each_group) # output: [('1', 7), ('2', 6), ('3', 5)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.