Python清单群组并加总更多栏位 [英] Python list group and sum with more fields

查看:106
本文介绍了Python清单群组并加总更多栏位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中包含两个我想求和的整数字段(字符串,整数,整数)

I have a list with two integer fields which I would like to sum (string,integer, integer)

myList= [[["26-07-2017",2,0], ["26-07-2017",3,0], ["27-07-2017",1,0], ["27-07-2017",0,1]]]

现在,我想按日期分组并汇总int字段.所以输出应该是这样的:

Now I would like to group by date and sum the int fields. So the output should be like this:

sumList= [[["26-07-2017",5,0], ["27-07-2017",1,1]]]

我该怎么做?谢谢你的回答.

How can I accomplish this? Thank you for the answer.

推荐答案

您可以使用

You can use itertools.groupby to group the items on the date, then use reduce to sum numbers in each group:

from itertools import groupby

lst = [[k] + reduce(lambda x, y: [y[1]+x[1], y[2]+x[2]], g) 
                          for k, g in groupby(myList[0], lambda x: x[0])]
print [lst]
# [[['26-07-2017', 5, 0], ['27-07-2017', 1, 1]]]

Python 3需要导入reduce:from functools import reduce

通过在f​​or循环中求和,您可以避免使用相对不那么精巧的reduce(也在提交到GvR中):

You could avoid using the relatively less intuitve reduce (also in submission to GvR) by taking the sums in a for loop:

from itertools import groupby

lst = []
for k, g in groupby(myList[0], lambda x: x[0]):
   g =  [sum(d) for d in zip(*(t[1:] for t in g))]
   lst.append([k] + g)
print [lst]
# [[['26-07-2017', 5, 0], ['27-07-2017', 1, 1]]]

这篇关于Python清单群组并加总更多栏位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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