
- Python 資料結構與演算法教程
- Python - 資料結構首頁
- Python - 資料結構介紹
- Python - 資料結構環境
- Python - 陣列
- Python - 列表
- Python - 元組
- Python - 字典
- Python - 二維陣列
- Python - 矩陣
- Python - 集合
- Python - 對映
- Python - 連結串列
- Python - 棧
- Python - 佇列
- Python - 雙端佇列
- Python - 高階連結串列
- Python - 雜湊表
- Python - 二叉樹
- Python - 搜尋樹
- Python - 堆
- Python - 圖
- Python - 演算法設計
- Python - 分治法
- Python - 遞迴
- Python - 回溯法
- Python - 排序演算法
- Python - 搜尋演算法
- Python - 圖演算法
- Python - 演算法分析
- Python - 大O表示法
- Python - 演算法類別
- Python - 均攤分析
- Python - 演算法論證
- Python 資料結構與演算法有用資源
- Python - 快速指南
- Python - 有用資源
- Python - 討論
Python - 對映
Python 對映,也稱為 ChainMap,是一種資料結構,用於將多個字典作為一個單元一起管理。組合字典包含按特定順序排列的鍵值對,消除了任何重複的鍵。ChainMap 的最佳用途是一次搜尋多個字典並獲取正確的鍵值對對映。我們還看到這些 ChainMap 的行為類似於棧資料結構。
建立 ChainMap
我們建立兩個字典,並使用 collections 庫中的 ChainMap 方法將它們組合在一起。然後,我們列印組合字典的結果的鍵和值。如果存在重複的鍵,則僅保留第一個鍵的值。
示例
import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day1': 'Thu'} res = collections.ChainMap(dict1, dict2) # Creating a single dictionary print(res.maps,'\n') print('Keys = {}'.format(list(res.keys()))) print('Values = {}'.format(list(res.values()))) print() # Print all the elements from the result print('elements:') for key, val in res.items(): print('{} = {}'.format(key, val)) print() # Find a specific value in the result print('day3 in res: {}'.format(('day1' in res))) print('day4 in res: {}'.format(('day4' in res)))
輸出
執行上述程式碼時,會產生以下結果:
[{'day1': 'Mon', 'day2': 'Tue'}, {'day1': 'Thu', 'day3': 'Wed'}] Keys = ['day1', 'day3', 'day2'] Values = ['Mon', 'Wed', 'Tue'] elements: day1 = Mon day3 = Wed day2 = Tue day3 in res: True day4 in res: False
對映重新排序
如果我們在上述示例中組合字典時更改字典的順序,我們會看到元素的位置會互換,就像它們在一個連續的鏈中一樣。這再次表明對映的行為類似於棧。
示例
import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day4': 'Thu'} res1 = collections.ChainMap(dict1, dict2) print(res1.maps,'\n') res2 = collections.ChainMap(dict2, dict1) print(res2.maps,'\n')
輸出
執行上述程式碼時,會產生以下結果:
[{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Thu'}] [{'day3': 'Wed', 'day4': 'Thu'}, {'day1': 'Mon', 'day2': 'Tue'}]
更新對映
當字典的元素被更新時,結果會立即在 ChainMap 的結果中更新。在下面的示例中,我們看到新更新的值會反映在結果中,而無需再次顯式應用 ChainMap 方法。
示例
import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day4': 'Thu'} res = collections.ChainMap(dict1, dict2) print(res.maps,'\n') dict2['day4'] = 'Fri' print(res.maps,'\n')
輸出
執行上述程式碼時,會產生以下結果:
[{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Thu'}] [{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day4': 'Fri'}]
廣告