python - 元组列表的列表,按第一个元素分组并添加第二个元素

标签 python list 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')
             ]
             # ...
         ]

我将如何根据第一个元素(日期)对它们进行分组并添加另一个元素。

例如我想要这样的东西:

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

最佳答案

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

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')]

关于python - 元组列表的列表,按第一个元素分组并添加第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43391333/

相关文章:

python 从文件中删除特定行

Swift:从元组中获取一个元素

list - Scala按属性对元组列表进行排序

python - python 有没有累积概率的函数

python - 如何解决 python 中的总线错误(核心转储)?

python - Ant 模拟: it's better to create a Process/Thread for each Ant or something else?

python - 使用 NumPy 查找元组列表第二个元素的中位数

python - 各时段活跃ID数

c++ - ERROR : list does not name a type (C++). 我不这么认为?

java - 使用 HashMap 索引对象列表是一种好习惯吗?