Python 中將列表轉換為類似鍵值對的列表


給定兩個單獨的列表,我們將透過將它們對映到一個鍵值資料結構(即字典)來將它們轉換為單個數據結構。第一個列表的值將作為鍵,第二個列表的值將作為字典中相應鍵的值。這種關係可以被認為是一對一或一對多,即一個鍵可以有多個值。

現在讓我們來看一個示例輸入和輸出,以便更好地理解如何在本文中將 Python 中的列表轉換為類似鍵值對的列表。

輸入

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

輸出

{3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

方法一:使用 Defaultdict 和 Zip

此方法使用 defaultdict 和列表作為預設值,這有助於有效地根據第一個列表 (list1) 中的對應元素對 list2 中的元素進行分組。之後,為了清晰起見,它將 defaultdict 轉換為常規字典,從而導致 list1 中的值與 list2 中的值列表的對映關係。

示例

from collections import defaultdict

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = defaultdict(list)

for key, value in zip(list1, list2):
   result_dict[key].append(value)

result_dict = dict(result_dict)
print("The first list is:",list1)
print("The second list is:",list2)
print("The mapped dictionary:",result_dict)

輸出

The first list is: [3, 4, 3, 4, 5, 5]
The second list is: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

方法二:使用迴圈和空字典

此方法建立一個名為 result_dict 的空字典。對於每一對,它會評估鍵(來自 list1 的元素)是否出現在 result_dict 中;如果不存在,則使用空列表初始化此鍵。隨後,它將來自 list2 的對應值(元素)新增到其關聯鍵的列表中:這有效地形成了一個字典,其中來自 list1 的元素作為鍵;但是,值由包含來自 list2 的關聯元素的列表組成。

示例

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {}

for key, value in zip(list1, list2):
   if key not in result_dict:
      result_dict[key] = []
   result_dict[key].append(value)

print("The mapped dictionary:",result_dict)

輸出

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

方法三:使用列表推導和 Defaultdict

這裡的 defaultdict 自動為每個鍵(來自 list1 的元素)建立列表;然後它將這個 defaultdict 轉換為一個普通的字典。最終結果:一個對映,其中鍵表現為來自 list1 的元素,而值則透過來自 list2 的關聯元素的列表出現。

示例

from collections import defaultdict

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = defaultdict(list)

[result_dict[key].append(value) for key, value in zip(list1, list2)]

result_dict = dict(result_dict)
print("The mapped dictionary:",result_dict)

輸出

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

方法四:使用字典推導

在 Python 中,我們可以透過字典推導簡潔地建立字典。程式碼“`{key: [] for key in set(list1)}`”構造一個字典,其中來自 list1 的唯一元素充當鍵;這些元素初始化為值為空列表。

示例

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {key: [] for key in set(list1)}

[result_dict[key].append(value) for key, value in zip(list1, list2)]
print("The mapped dictionary:",result_dict)

輸出

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

方法五:使用 Defaultdict 和 itertools.groupby

Defaultdict(list) 命令啟用一個字典;這個新啟動的字典等待缺失的鍵,所有這些鍵都將由空列表填充。groupby 函式根據第一個值對對進行分類 - lambda x: x[0] 表示此類分組的鍵。因此,list1 和 list2 元素透過執行此程式碼段進行排序和後續分組到 result_dict 中。

示例

from collections import defaultdict
from itertools import groupby

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

sorted_lists = sorted(zip(list1,list2), key=lambda x: x[0])

result_dict = defaultdict(list)

for key, group in groupby(sorted_lists, key=lambda x: x[0]):
   result_dict[key].extend(item[1] for item in group)

result_dict = dict(result_dict)
print("The mapped dictionary:",result_dict)

輸出

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

方法六:使用 Collections 模組中的 Counter

使用 Counter,此程式碼計算 list1 中元素的出現次數;然後它使用 zip 迴圈遍歷 list1 和 list2,這是一種確保每個鍵(來自 list1 的元素)與值陣列(來自 list2 的元素)對齊的方法。精確地,Counter 保持每個可用例項的最新記錄:透過這樣做,我們避免了結果字典中的重複。

示例

from collections import Counter

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {}
counter = Counter(list1)

for key, value in zip(list1, list2):
   if counter[key] > 0:
      if key not in result_dict:
         result_dict[key] = []
      result_dict[key].append(value)
      counter[key] -= 1
print("The mapped dictionary:",result_dict)

輸出

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

方法七:使用 zip 和 itertools.groupby

此方法首先對列表進行排序,然後使用 groupby 對排序後的對進行分組,從而形成一個 result_dict,其中鍵來自 list 1,值來自 list2。

示例

from itertools import groupby
from operator import itemgetter

list1 = [3, 4, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

sorted_lists = sorted(zip(list1,list2), key=itemgetter(0))

result_dict = {key: [x[1] for x in group] for key, group in groupby(sorted_lists, key=itemgetter(0))}

print("The mapped dictionary:",result_dict)

輸出

The mapped dictionary: {3: ['apple', 'cherry'], 4: ['banana', 'date'], 5: ['elderberry', 'fig']}

方法八:使用 for 迴圈和 setdefault

使用 zip 函式並行迭代兩個列表 list1 和 list2,將它們合併在一起。接下來是建立一個字典 result_dict;在這裡,它將 list1 中的元素賦值為鍵,並將 list2 中的元素分組到列表中作為相應的鍵值。setdefault 方法初始化任何前所未有的字典鍵,此過程確保 list1 上的值與其在 list2 上的關聯值集之間成功對映。

示例

list1 = [3, 4, 3, 4, 5, 3]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

result_dict = {}

for key, value in zip(list1, list2):
   result_dict.setdefault(key, []).append(value)

print("The mapped dictionary:",result_dict)

輸出

The mapped dictionary: {3: ['apple', 'cherry', 'fig'], 4: ['banana', 'date'], 5: ['elderberry']}

方法九:使用 itertools 的 groupby 函式

此程式碼合併兩個列表:list1 和 list2。最初,它根據 list1 中的元素對它們進行排序;隨後,itertools.groupby 發揮作用以對具有相同鍵的元素進行分組 - 導致一個名為 result_dict 的字典。在此目錄中,從 list1 派生的唯一元素作為鍵,而 List2 中的關聯元件用作值。

示例

from itertools import groupby

list1 = [5, 0, 3, 4, 5, 5]
list2 = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

sorted_lists = sorted(zip(list1, list2), key=lambda x: x[0])

result_dict = {key: [item[1] for item in group] for key, group in groupby(sorted_lists, key=lambda x: x[0])}

print("The mapped dictionary:",result_dict)

輸出

The mapped dictionary: {0: ['banana'], 3: ['cherry'], 4: ['date'], 5: ['apple', 'elderberry', 'fig']}

結論

我們展示了建立兩個單獨列表的對映字典的不同方法。透過建立這些列表中元素之間的關聯,這些程式碼演示瞭如何有效地管理資料;同時容納一對一和一對多的關係。每種方法都有其自身的優缺點,但是理解每一種方法可以幫助程式設計師更好地掌握 Python。

更新於:2023年11月2日

瀏覽量 128

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告