Python 中元組列表的分組求和


當需要查詢元組列表的分組和時,需要使用“計數器”方法和“+”運算子。

“計數器”是一個有助於對可雜湊物件進行計數的子類,即當它被呼叫時,它會自己建立雜湊表(可迭代的物件,如列表、元組等)。

它返回一個迭代工具,用於獲取所有非零值的元素作為計數。

“+”運算子可用於新增數字值或連線字串。

以下是相同的演示 −

示例

即時演示

from collections import Counter

my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)]
my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)]

print("The first list is : ")
print(my_list_1)
print("The second list is : " )
print(my_list_2)

cumulative_val_1 = Counter(dict(my_list_1))
cumulative_val_2 = Counter(dict(my_list_2))
cumulative_val_3 = cumulative_val_1 + cumulative_val_2  
my_result = list(cumulative_val_3.items())

print("The grouped summation of list of tuple is : ")
print(my_result)

輸出

The first list is :
[('Hi', 14), ('there', 16), ('Jane', 28)]
The second list is :
[('Jane', 12), ('Hi', 4), ('there', 21)]
The grouped summation of list of tuple is :
[('Hi', 18), ('there', 37), ('Jane', 40)]

說明

  • 匯入所需的包。
  • 定義兩個元組列表,並在控制檯上顯示。
  • 這兩個元組列表都轉換為字典。
  • 它們使用“+”運算子進行相加。
  • 此結果轉換為列表,僅使用字典的“值”。
  • 此操作的資料儲存在一個變數中。
  • 此變數是顯示在控制檯上的輸出。

更新於: 2021 年 3 月 13 日

130 次瀏覽

開啟你的事業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.