Python - 元組列表中根據第二個元素對第一個元素進行分組


在 Python 中,可以根據元組列表中第二個元素的值對元素進行分組,可以使用多種方法,例如使用字典或使用 itertools.groupby() 方法,以及使用 collections 中的 defaultdict。根據元組列表中第二個元素對第一個元素進行分組,意味著具有相同第二個元素的元組可以被分組到同一個元素組中。在本文中,我們將討論如何實現這些方法,以便我們能夠輕鬆地根據元組列表中的第二個元素對第一個元素進行分組。

方法 1:使用字典

此方法涉及使用字典對元素進行分組。這種方法利用字典的鍵值對來儲存第一個元素,並使用第二個元素作為鍵。

語法

dict_name[key]

在這裡,方括號表示法用於為字典中的特定鍵賦值。如果鍵已存在,則將值追加到與該鍵關聯的列表中;否則,將建立一個新的鍵值對。

示例

在下面的示例中,我們首先初始化一個空字典 grouped_data。然後,對於資料列表中的每個元組,我們提取第二個元素作為鍵 (item[1]) 和第一個元素作為值 (item[0])。然後,我們檢查鍵是否已存在於 grouped_data 中。如果存在,我們將值追加到與該鍵關聯的值的現有列表中。否則,我們建立一個新的鍵值對,其中鍵是第二個元素,值是包含第一個元素的新列表。然後最後,我們遍歷 grouped_data 字典並列印每個鍵及其對應值。

# Sample tuple list
data = [('Apple', 'Fruit'), ('Banana', 'Fruit'), ('Carrot', 'Vegetable'), ('Potato', 'Vegetable')]

# Grouping elements using a dictionary
grouped_data = {}
for item in data:
    key = item[1]
    value = item[0]
    if key in grouped_data:
        grouped_data[key].append(value)
    else:
        grouped_data[key] = [value]

# Printing the grouped data
for key, values in grouped_data.items():
    print(key, ":", values)

輸出

Fruit : ['Apple', 'Banana']
Vegetable : ['Carrot', 'Potato']

方法 2:使用 itertools.groupby()

itertools.groupby() 函式提供了一種根據特定條件對元素進行分組的有效方法。此方法要求輸入資料根據第二個元素進行排序。

語法

   groups[key]

在這裡,來自 itertools 模組的 groupby() 函式遍歷 groupby 物件。該函式返回鍵和一組具有相同值的連續項。然後使用鍵和組在 groups 字典中建立鍵值對,其中鍵是唯一值,值是分組項的列表。

示例

在下面的示例中,我們從 itertools 模組匯入 groupby() 函式。groupby() 函式要求輸入資料根據分組鍵進行排序。因此,我們使用 sorted() 函式對資料列表進行排序,並提供一個 lambda 函式作為 key 引數以指定根據第二個元素 (x[1]) 進行排序。然後,我們遍歷 groupby() 函式的輸出,它返回一個鍵和一個分組元素的迭代器。對於每個組,我們提取鍵並建立一個對應第一個元素 (item[0]) 的列表。

from itertools import groupby

# Sample tuple list
data = [('Apple', 'Fruit'), ('Banana', 'Fruit'), ('Carrot', 'Vegetable'), ('Potato', 'Vegetable')]

# Sorting the data based on the second element
sorted_data = sorted(data, key=lambda x: x[1])

# Grouping elements using itertools.groupby()
grouped_data = {}
for key, group in groupby(sorted_data, key=lambda x: x[1]):
    grouped_data[key] = [item[0] for item in group]

# Printing the grouped data
for key, values in grouped_data.items():
    print(key, ":", values)

輸出

Fruit : ['Apple', 'Banana']
Vegetable : ['Carrot', 'Potato']

方法 3:使用 collections 中的 defaultdict

collections 模組中的 defaultdict 類提供了一種方便的方法來對元組列表中的元素進行分組。它會自動為每個鍵建立一個新的列表作為預設值,從而簡化了分組過程。

語法

groups[item].append(item)

在這裡,語法使用 collections 模組中的 defaultdict() 函式初始化一個名為 groups 的 defaultdict 物件,其預設值為一個空列表。第二行程式碼使用鍵 (item) 訪問 groups 字典中與該鍵關聯的列表,並將 item 追加到列表中。

示例

在下面的示例中,我們從 collections 模組匯入 defaultdict 類。在初始化 grouped_data 字典時,我們使用 defaultdict(list) 將預設值設定為一個空列表。然後,我們遍歷資料列表,提取第二個元素作為鍵 (item[1]) 和第一個元素作為值 (item[0])。透過使用 defaultdict,我們可以直接將值追加到與該鍵關聯的列表中。

from collections import defaultdict

# Sample tuple list
data = [('Apple', 'Fruit'), ('Banana', 'Fruit'), ('Carrot', 'Vegetable'), ('Potato', 'Vegetable')]

# Grouping elements using defaultdict
grouped_data = defaultdict(list)
for item in data:
    grouped_data[item[1]].append(item[0])

# Printing the grouped data
for key, values in grouped_data.items():
    print(key, ":", values)

輸出

Fruit : ['Apple', 'Banana']
Vegetable : ['Carrot', 'Potato']

結論

在本文中,我們討論瞭如何在 Python 中使用不同的方法根據元組列表中的第二個元素對第一個元素進行分組。透過使用字典,我們可以輕鬆地儲存和訪問分組資料。itertools.groupby() 函式提供了一種有效的解決方案,但要求資料已排序。此外,defaultdict 類透過自動為每個鍵建立列表作為預設值來簡化分組過程。

更新於: 2023年7月18日

617 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.