如何按首元素對 Python 元組元素分組?


Python 有一個名為 defaultdict 的函式,它按首元素對 Python 元組元素進行分組。

示例

lst = [
   (1, 'Hello', 'World', 112),
   (2, 'Hello', 'People', 42),
   (2, 'Hi', 'World', 200)
]

from collections import defaultdict

d = defaultdict(list)
for k, *v in lst:
   d[k].append(v)
print(d)

輸出

這將給出輸出

defaultdict(<class 'list'>, {1: [['Hello', 'World', 112]], 2: [['Hello', 'People', 42], ['Hi', 'World', 200]]})

使用 tuple(d.items()) 方法,可以在保持分組的同時將其轉換回元組。 

示例

print(tuple(d.items()))

輸出

這將給出輸出

((1, [['Hello', 'World', 112]]), (2, [['Hello', 'People', 42], ['Hi', 'World', 200]]))

更新時間:2020 年 03 月 05 日

565 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.