![](/img/trans.png)
[英]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.