python ChainMap管理用法實例講解
1、ChainMap的主要用例是提供一種有效的方法來管理多個范圍或上下文,并處理重復鍵的訪問優先級。
2、當有多個存儲重復鍵的字典訪問它們的順序時,這個功能非常有用。
在ChainMap文檔中找到一個經典的例子,它模擬Python如何分析不同命名空間中的變量名稱。
當Python搜索名稱時,它會依次搜索當地、全局和內置的功能域,直到找到目標名稱。Python作用域是將名稱映射到對象的字典。
為了模擬Python的內部搜索鏈,可以使用鏈映射。
實例>>> import builtins >>> # Shadow input with a global name>>> input = 42 >>> pylookup = ChainMap(locals(), globals(), vars(builtins)) >>> # Retrieve input from the global namespace>>> pylookup['input']42 >>> # Remove input from the global namespace>>> del globals()['input'] >>> # Retrieve input from the builtins namespace>>> pylookup['input']<built-in function input>
知識點擴展:
ChainMap類管理的是一個字典序列,并按其出現的順序搜索以查找與鍵關聯的值。ChainMap提供了一個很好的“上下文”容器,因此可以把它看成一個棧,棧增長時發生變更,棧收縮時這些變更被丟棄。
下面,我們來看看其基本的使用規則:
import collectionsa = {'a': 'A', 'c': 'c', }b = {'b': 'B', 'c': 'D', }col = collections.ChainMap(a, b)# 和普通字典一樣訪問print(col['a'])print(list(col.keys()), list(col.values()))for key, value in col.items(): print(key, value)
可以看到,在相同的key值情況下,只有子映射a的值。這也就是說明ChainMap是按子映射傳遞到構造函數的順序來搜索這些子映射。
以上就是python ChainMap管理用法實例講解的詳細內容,更多關于python ChainMap的管理用法的資料請關注好吧啦網其它相關文章!
相關文章: