Python在字典列表中的元组中的值求和? [英] Python sum values in tuple in a list in a dictionary?

查看:1420
本文介绍了Python在字典列表中的元组中的值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的词典中,每个条目都有一个元组列表(我的python语法可能是错误的,请多多包涵.)看起来像这样:

In my dictionary, each entry has a list of tuples (my python grammar may be wrong, please bear with me). It looks something like this:

{1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)],...}

我想对每个条目的元组中的第二个值求和,即:

I'd like to sum the second value in the tuple for each entry, i.e.:

{1: (10), 2: (5)...}

我一直在使用

result = sum(y for v in dict.itervalues() for (x, y) in v)

但是它将两个条目的所有值相加.

But it adds up all of the values for both entries.

推荐答案

您可以执行以下操作:

感谢@ vaultah的评论.

Thanks to @ vaultah's comment.

a = {1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)]}
final = {k:(sum(j for _,j in v),) for k,v in a.items()}
print(final)

Output:

>>> {1: (10,), 2: (6,)}

这篇关于Python在字典列表中的元组中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆