繁体   English   中英

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

[英]List of lists of tuples, group by first element and add second elements

假设我有以下元组列表列表:

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

首先,将元组列表从元组列表中取出,然后使用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)]

我的方法是将嵌套列表转换为平面列表并对其进行迭代:

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

展平列表,然后使用 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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM