如何在按第一个值分组的元组列表中获取第二个和第三个值的总和?
即:
list_of_tuples = [(1, 3, 1), (1, 2, 4), (2, 1, 0), (2, 2, 0)]
expected_output = [(1, 5, 5), (2, 3, 0)]
我在StackOverflow上发现了几个great answers,发现这个元组有两个值,但是无法弄清楚如何调整它们来对第二个和第三个值求和。
第二个值的一个好答案是:
def sum_pairs(pairs):
sums = {}
for pair in pairs:
sums.setdefault(pair[0], 0)
sums[pair[0]] += pair[1]
return sums.items()
答案 0 :(得分:3)
你也可以这样做:
list_of_tuples = [(1, 3, 1), (1, 2, 4), (2, 1, 0), (2, 2, 0)]
# create empty dictionary to store data
sums = {}
# iterate over list of typles
for pair in list_of_tuples:
# create new item in dictionary if it didnt exist
if pair[0] not in sums: sums[pair[0]] = [pair[0], 0 ,0]
# sum the values
sums[pair[0]][1] += pair[1]
sums[pair[0]][2] += pair[2]
#print resulting tuple
print(tuple(sums.values()))
答案 1 :(得分:1)
您可以使用itertools.groupby
根据第一项进行分组,然后获取每组中所有最后两项的累计总和:
from itertools import groupby
list_of_tuples = [(1, 3, 1), (1, 2, 4), (2, 1, 0), (2, 2, 0)]
lst = [(k,)+tuple(sum(x) for x in zip(*g))[1:]
for k, g in groupby(list_of_tuples, lambda x: x[0])]
print(lst)
# [(1, 5, 5), (2, 3, 0)]
答案 2 :(得分:1)
使用defaultdict
作为石斑鱼:
>>> from collections import defaultdict
>>> grouper = defaultdict(lambda: (0,0))
>>> list_of_tuples = [(1, 3, 1), (1, 2, 4), (2, 1, 0), (2, 2, 0)]
>>> for a, b, c in list_of_tuples:
... x, y = grouper[a]
... grouper[a] = (x + b, y + c)
...
>>> grouper
defaultdict(<function <lambda> at 0x102b240d0>, {1: (5, 5), 2: (3, 0)})
现在,您可以随时获取这样的元组列表:
>>> [(k, a, b) for k, (a, b) in grouper.items()]
[(1, 5, 5), (2, 3, 0)]