如何获取将python字典的总和列为元组?

发布于 2025-02-07 21:47:49 字数 370 浏览 6 评论 0原文

我的python词典被列为如下所示;在这里,每个元组的第一个值描绘了组号,每个字典描述了与组内部的每个数字相关的生成值(ie,{'1':0,'3':1,'2':1, ,'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)]

'5': 2 这种方法是如此昂贵。

I have python dictionary listed as tuples as follows; Here the first value of the each tuple depicts the group number and each dictionary depicts the generated value related to the each number inside the group, (i.e., {'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})]

Is there any method to get the sum of the each group by getting the sum of the each group, (i.e.,

[('1', 7), ('2', 6), ('3', 5)]

I tried to iterate over the each value and get the sum but that method is so expensive.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丘比特射中我 2025-02-14 21:47:49

一个简单的列表理解应该如此

>>> [(k, sum(dic.values())) for k, dic in tuples]

A simple list comprehension should so

>>> [(k, sum(dic.values())) for k, dic in tuples]
等往事风中吹 2025-02-14 21:47:49
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)]
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)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文