簡體   English   中英

Python元組列表中第二個和第三個元素的和,按第一個分組

[英]Python sum of second and third element of tuple in list of tuples grouped by first

如何獲得按第一個值分組的元組列表中第二個和第三個值的總和?

即:

list_of_tuples = [(1, 3, 1), (1, 2, 4), (2, 1, 0), (2, 2, 0)]

expected_output = [(1, 5, 5), (2, 3, 0)]

我在StackOverflow上找到了幾個不錯的答案 ,這樣做可以找到具有兩個值的元組,但無法弄清楚如何調整它們以求第二個和第三個值之和。

對於第二個值,很好的答案之一是:

def sum_pairs(pairs):
sums = {}
for pair in pairs:
    sums.setdefault(pair[0], 0)
    sums[pair[0]] += pair[1]
return sums.items()

您也可以這樣:

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

您可以使用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)]

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM