使用python对列表中的相同键的多个值求和 [英] Sum multiple values for same key in lists using python

查看:578
本文介绍了使用python对列表中的相同键的多个值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表:

I have a list which looks like this:

(151258350, 2464)
(151258350, 56)
(151262958, 56)
(151258350, 56)
(151262958, 112)
(151262958, 112)
(151259627, 56)
(151262958, 112)
(151262958, 56)

我想要一个看起来像这样的结果:

And I want a result that looks like this:

151259627 56
151262958 448
151258350 2576

这是我的代码:

for key, vals in d.items():
    tempList.append((key, reduce(add, vals))) 

在这里,d是具有键-值对的列表. tempList是一个列表,在通过键求和之后,将在其中附加值.并添加一个功能:

here, d is the list with the key-value pair. tempList is the List in which the values will be appended after summing them by key. and add is a fuction:

def add(x, y): return x+y

如果已经问过这个问题,请把我指向那里,因为我自己找不到它.

If this question has already been asked, please point me there as I was unsuccessful in finding it myself.

推荐答案

num_list = [(151258350, 2464),
(151258350, 56),
(151262958, 56),
(151258350, 56),
(151262958, 112),
(151262958, 112),
(151259627, 56),
(151262958, 112),
(151262958,56)]
num_dict = {}
for t in num_list:
    if t[0] in num_dict:
        num_dict[t[0]] = num_dict[t[0]]+t[1]
    else:
        num_dict[t[0]] = t[1]

for key,value in num_dict.items():
    print "%d %d" %(key,value)

这篇关于使用python对列表中的相同键的多个值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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