最近發現的python內置庫(一)——collections

這個模塊實現了特定目標的容器,以提供Python標準內建容器 dict , list , set , 和 tuple 的替代選擇。

方法名 說明
namedtuple() 創建命名元組子類的工廠函數
deque 類似列表(list)的容器,實現了在兩端快速添加(append)和彈出(pop)
ChainMap 類似字典(dict)的容器類,將多個映射集合到一個視圖裏面
Counter 字典的子類,提供了可哈希對象的計數功能
OrderedDict 字典的子類,保存了他們被添加的順序
defaultdict 字典的子類,提供了一個工廠函數,爲字典查詢提供一個默認值
UserDict 封裝了字典對象,簡化了字典子類化
UserList 封裝了列表對象,簡化了列表子類化
UserString 封裝了列表對象,簡化了字符串子類化

ChainMap

一個 ChainMap 類是爲了將多個映射快速的鏈接到一起,這樣它們就可以作爲一個單元處理。它通常比創建一個新字典和多次調用 update() 要快很多。
這個類可以用於模擬嵌套作用域,並且在模版化的時候比較有用。
此方法可用於從多個可映射對象中查找某個鍵值對的時候使用,需要注意的是,對於同名的鍵,返回先出現的鍵值對。

class collections.ChainMap(*maps)

  • maps: 一個可以更新的映射列表。這個列表是按照第一次搜索到最後一次搜索的順序組織的。它是僅有的存儲狀態,可以被修改。列表最少包含一個映射。

  • new_child(m=None): d.new_child() 調用等價於 ChainMap({}, *d.maps) 。這個方法用於創建子上下文,不改變任何父映射的值。

  • parents: d.parents 的引用等價於 ChainMap(*d.maps[1:]) 。

>>> baseline = {'music': 'bach', 'art': 'rembrandt'}
>>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
>>> list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']

# 等價於
>>> combined = baseline.copy()
>>> combined.update(adjustments)
>>> list(combined)
['music', 'art', 'opera']

ChainMap的擴展用例

  • 模擬Python內部lookup鏈的例子
import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))
  • 讓用戶指定的命令行參數優先於環境變量,優先於默認值的例子
import os, argparse

defaults = {'color': 'red', 'user': 'guest'}

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = {k: v for k, v in vars(namespace).items() if v is not None}

combined = ChainMap(command_line_args, os.environ, defaults)
print(combined['color'])
print(combined['user'])
  • 用 ChainMap 類模擬嵌套上下文的例子
c = ChainMap()        # Create root context
d = c.new_child()     # Create nested child context
e = c.new_child()     # Child of c, independent from d
e.maps[0]             # Current context dictionary -- like Python's locals()
e.maps[-1]            # Root context -- like Python's globals()
e.parents             # Enclosing context chain -- like Python's nonlocals

d['x'] = 1            # Set value in current context
d['x']                # Get first key in the chain of contexts
del d['x']            # Delete from current context
list(d)               # All nested values
k in d                # Check all nested values
len(d)                # Number of nested values
d.items()             # All nested items
dict(d)               # Flatten into a regular dictionary
  • ChainMap 類只更新鏈中的第一個映射,但lookup會搜索整個鏈。 然而,如果需要深度寫和刪除,也可以很容易的通過定義一個子類來實現它
class DeepChainMap(ChainMap):
    'Variant of ChainMap that allows direct updates to inner scopes'

    def __setitem__(self, key, value):
        for mapping in self.maps:
            if key in mapping:
                mapping[key] = value
                return
        self.maps[0][key] = value

    def __delitem__(self, key):
        for mapping in self.maps:
            if key in mapping:
                del mapping[key]
                return
        raise KeyError(key)

>>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'})
>>> d['lion'] = 'orange'         # update an existing key two levels down
>>> d['snake'] = 'red'           # new keys get added to the topmost dict
>>> del d['elephant']            # remove an existing key one level down
>>> d                            # display result
DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})

------施工中------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章