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

时间:2017-04-13 11:40:15

标签: 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')],

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

首先,从元组列表列表中展开元组列表,然后使用itertools.groupby

import itertools 
import operator

lists = [
         [('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')]
         ]

# Step 1: Flat a list of tuples out of a list of lists of tuples
list_tuples = [t for sublist in lists for t in sublist]
'''
[('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')]
'''

# Step 2: Groupby
results = list()

for key, group in itertools.groupby(sorted(list_tuples), operator.itemgetter(0)):
    s = sum(float(t[1]) for t in group)
    results.append((key, s))

print(results)
#[('2017-04-11', 2000000.0), ('2017-04-12', 1472943.0), ('2017-04-13', 4000000.0)]

答案 2 :(得分:0)

我的方法是将嵌套列表转换为平面列表并迭代它:

t = [
         [('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')]
         ]
a={}

for i,j in sum(t,[]):
    a[i]=a[i]+float(j) if i in a else float(j)

print(a)

输出:

{'2017-04-11': 2000000.0, '2017-04-13': 4000000.0, '2017-04-12': 1472943.0}

如果您需要列表,可以使用[(k,v) for k,v in a.items()])

答案 3 :(得分:0)

使用defaultdict展平列表:

from collections import defaultdict

flattened_tuples = [item for sublist in tuples for item in sublist]

result = defaultdict(float)
for date, value in flattened_tuples:
    result[date] += float(value)
print(result)

返回 {'2017-04-11': 2000000.0, '2017-04-12': 1472943.0, '2017-04-13': 4000000.0}