元组列表列表,按第一个元素分组并添加第二个元素 [英] List of lists of tuples, group by first element and add second elements

查看:159
本文介绍了元组列表列表,按第一个元素分组并添加第二个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有以下元组列表:

Let's say I have the following list of lists of tuples:

tuples = [
             [ 
                 ('2017-04-11', '2000000.00'), 
                 ('2017-04-12', '1000000.00'), 
                 ('2017-04-13', '3000000.00')
             ],
             [
                 ('2017-04-12', '472943.00'), 
                 ('2017-04-13', '1000000.00')
             ]
             # ...
         ]

如何根据第一个元素(日期)对它们进行分组,然后添加另一个元素.

How would I go about grouping them based off of the first element (date) and adding the other element.

例如,我想要这样的东西:

For instance I'd like something like this:

tuples = [('2017-04-11', '2000000.00'), ('2017-04-12', '1472943.00'), ('2017-04-13', '4000000.00')],

推荐答案

使用itertools.chain.from_iterableitertools.groupbysum函数的解决方案:

The solution using itertools.chain.from_iterable, itertools.groupby and sum functions:

import itertools, operator

tuples = [
         [('2017-04-11', '2000000.00'), ('2017-04-12', '1000000.00'), ('2017-04-13', '3000000.00')],
         [('2017-04-12', '472943.00'), ('2017-04-13', '1000000.00')]
         ]

result = [(k, "%.2f" % sum(float(t[1]) for t in g)) 
          for k,g in itertools.groupby(sorted(itertools.chain.from_iterable(tuples)), operator.itemgetter(0))]

print(result)

输出:

[('2017-04-11', '2000000.00'), ('2017-04-12', '1472943.00'), ('2017-04-13', '4000000.00')]

这篇关于元组列表列表,按第一个元素分组并添加第二个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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