Python – 將相似項分組到字典值列表中


在資料分析和處理中,為了更好地組織和分析資料,需要將相似元素分組。Python 提供了幾種方法來高效地將元素分組到字典值列表中,例如使用 for 迴圈、使用 defaultdict 和使用 itertools.groupby 方法。在本文中,我們將探討在 Python 中將相似項分組到字典值列表的不同方法。

方法一:使用 for 迴圈

將相似項分組到字典值列表中最簡單的方法是使用 for 迴圈。讓我們考慮一個例子,我們有一系列水果,我們想根據它們各自的顏色對它們進行分組。

語法

list_name.append(element)

這裡,append() 函式是一個列表方法,用於將元素新增到列表_name 的末尾。它透過將指定的元素作為新專案新增到列表中來修改原始列表。

示例

在下面的示例中,我們迭代“fruits”列表中的每個水果。對於每個水果,我們提取其顏色。如果顏色已存在於“color_dict”字典中,我們將水果名稱新增到相應的列表中。否則,我們在字典中建立一個新的鍵值對,其中鍵是顏色,值是包含水果名稱的列表。

fruits = [
    {"name": "apple", "color": "red"},
    {"name": "banana", "color": "yellow"},
    {"name": "grape", "color": "purple"},
    {"name": "orange", "color": "orange"},
    {"name": "kiwi", "color": "green"},
    {"name": "strawberry", "color": "red"}
]

color_dict = {}

for fruit in fruits:
    color = fruit["color"]
    if color in color_dict:
        color_dict[color].append(fruit["name"])
    else:
        color_dict[color] = [fruit["name"]]

print(color_dict)

輸出

{'red': ['apple', 'strawberry'], 'yellow': ['banana'], 'purple': ['grape'], 'orange': ['orange'], 'green': ['kiwi']}

方法二:使用 collections 模組中的 defaultdict

使用 Python 的 collections 模組,我們可以使用**defaultdict**類,簡化了分組項的過程。此類會自動使用預設值初始化字典的任何新鍵。

語法

groups = defaultdict(list)
groups[item].append(item)

這裡,defaultdict() 函式建立一個名為 groups 的 defaultobject。第二行程式碼使用鍵 (item) 來訪問與 groups 字典中該鍵關聯的列表,並將 item 附加到列表中。

示例

在下面的示例中,透過使用 defaultdict 類,我們無需在將專案新增到字典之前進行顯式檢查。我們將**“color_dict”**初始化為一個 defaultdict,其預設值為列表。當訪問新鍵時,如果它不存在,defaultdict 會自動建立一個空列表作為其值。因此,我們可以直接將水果名稱附加到相應的列表中,而無需擔心鍵是否存在。

from collections import defaultdict

fruits = [
    {"name": "apple", "color": "red"},
    {"name": "banana", "color": "yellow"},
    {"name": "grape", "color": "purple"},
    {"name": "orange", "color": "orange"},
    {"name": "kiwi", "color": "green"},
    {"name": "strawberry", "color": "red"}
]

color_dict = defaultdict(list)

for fruit in fruits:
    color_dict[fruit["color"]].append(fruit["name"])

print(color_dict)

輸出

defaultdict(, {'red': ['apple', 'strawberry'], 'yellow': ['banana'], 'purple': ['grape'], 'orange': ['orange'], 'green': ['kiwi']})

方法三:使用 itertools.groupby

我們可以使用 Python 的 itertools 模組來處理迭代器。groupby 函式允許我們根據特定條件對專案進行分組。讓我們考慮一個例子,我們有一系列單詞,我們想根據它們的第一個字母對它們進行分組。

語法

list_name.append(element)

這裡,append() 函式是一個列表方法,用於將元素新增到列表_name 的末尾。它透過將指定的元素作為新專案新增到列表中來修改原始列表。

itertools.groupby(iterable, key=None)

這裡,iterable 是任何應用 groupby() 的元素集合。key 是可選引數,它是用作分組鍵的函式。

示例

在下面的示例中,我們使用**key_func** lambda 函式來提取每個單詞的第一個字母。我們對單詞列表進行排序,以確保將相似的專案分組在一起。groupby 函式返回一個迭代器,該迭代器根據 key_func 提供連續的鍵和組。我們將組迭代器轉換為列表,並將其作為“word_dict”中每個鍵的值。

import itertools

words = ["apple", "banana", "cat", "dog", "elephant", "ant"]

key_func = lambda x: x[0]
words.sort()

word_dict = {}

for key, group in itertools.groupby(words, key_func):
    word_dict[key] = list(group)

print(word_dict)

輸出

{'a': ['ant', 'apple'], 'b': ['banana'], 'c': ['cat'], 'd': ['dog'], 'e': ['elephant']}

結論

在本文中,我們討論瞭如何使用 Python 中的各種方法將相似項分組到字典值列表中。我們首先使用簡單的 for 迴圈,然後使用 collections 模組中的 defaultdict 類,最後使用 itertools 模組中的 groupby 函式。每種方法都有其優點,可以根據手頭任務的具體要求進行選擇。

更新於:2023年7月19日

瀏覽量 179

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告