Python collections模塊中的幾種數(shù)據(jù)結構

Python collections模塊中的幾種數(shù)據(jù)結構

namedtuple

  • namedtuple 是一種類似于元組的數(shù)據(jù)類型,除了 tuple 的一些用法之外,還能更方便地通過屬性名來訪問數(shù)據(jù)
In[1]: from collections import namedtuple
In[2]: Person = namedtuple('Person', ['name', 'age',  'phone'])
In[3]: me = Person(name='me', age='1', phone=123465)
In[4]: me
Out[4]: Person(name='me', age='1', phone=123465)

從上面的例子中可以看出,當使用 nametuple 通過屬性訪問數(shù)據(jù)時,能讓我們的代碼更好維護(與索引相比)

def fun1():
    ...
    return code, message

code, message = fun1()


Result = namedtuple('Recult', ['code', 'success'])
def fun2():
    ...
    return Result(code=0, message='success')

result = func2()

從上面兩種函數(shù)的返回方式來看,第二種的可讀性是比第一種好的,尤其是當一次返回多個數(shù)據(jù),又不想將返回結果封裝成一個 class的時候,可以使用 nametuple

  • 不可變

    • tuple 類似,namedtuple的屬性是不可變的
    In[5]: me.age += 1
    Traceback (most recent call last):
    File "/home/liujinxuan/Virtualenv/venv/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2878, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
    File "<ipython-input-6-99c261b82013>", line 1, in <module>
        me.age += 1
    TypeError: cannot concatenate 'str' and 'int' objects
    
  • 更多用法,參考 https://docs.python.org/2/library/collections.html#collections.namedtuple

deque

  • deque 對象類似于list列表,不過你可以操作它的“兩端”, 是一個高效實現(xiàn)插入和刪除操作的雙向列表,適合用于隊列和棧

    In[1]: from collections import deque
    In[2]: q = deque()
    In[3]: q.append(0)
    In[4]: q.append(1)
    In[5]: q
    Out[5]: deque([0, 1])
    In[6]: q.appendleft(2)
    In[7]: q
    Out[7]: deque([2, 0, 1])
    In[8]: q.pop()
    Out[8]: 1
    In[9]: q.popleft()
    Out[9]: 2
    
  • 我們可以從任一端擴展這個隊列中的數(shù)據(jù):

    In[10]: d.extendleft([d.extend([6,7,8])])
    Out[10]: deque([6, 7, 8, 0])
    
  • 我們也可以設置 deque 的大小,當元素數(shù)量超出設定的限制時,數(shù)據(jù)會從另一端被 pop 出去

    In[11]: d = deque(maxlen=5)
    In[11]: d.extend([6, 7, 8, 0])
    In [12]: d
    Out[13]: deque([6, 7, 8, 0, 1])
    In [14]: d.append(2)
    In [15]: d
    Out[15]: deque([7, 8, 0, 1, 2])
    In [16]: d.appendleft(6)
    In [17]: d
    Out[17]: deque([6, 7, 8, 0, 1])
    
    
  • 更多用法, 參考 https://docs.python.org/2/library/collections.html#collections.deque

defaultdict

  • defaultdict 的用法與 dict 類似, 不同的是, 當訪問 defaultdict 中不存在的值時,會返回一個默認值,而不是向 dict 引發(fā)KeyError異常

  • defaultdict 類的初始化函數(shù)接受一個類型作為參數(shù),當所訪問的鍵不存在的時候,可以實例化一個值作為默認值:

    In [1]: from collections import defaultdict
    In [2]: d = defaultdict(list)
    In [3]: d['not_exist_key']
    Out[3]: []
    In [4]: def init_value():
        ...:     return 0
        ...: 
    In [5]: d = defaultdict(init_value)
    In [6]: d['not_exist_key']
    Out[6]: 0
    
  • 這種形式的默認值只有在通過 dict[key] 或者 dict.__getitem__(key) 訪問的時候才有效

    >>> from collections import defaultdict
    >>> print defaultdict.__missing__.__doc__
    __missing__(key) # Called by __getitem__ for missing key; pseudo-code:
    if self.default_factory is None: raise KeyError((key,))
    self[key] = value = self.default_factory()
    return value
    

    defaultdict 實現(xiàn)了 __missing__ 方法, __missing__ 方法的作用是當使用 __getitem__() 方法訪問一個不存在的鍵時( dict[key] 這種形式實際上是 __getitem__() 方法的簡化形式),會調(diào)用 __missing__() 方法獲取默認值,并將該鍵添加到字典中去。

  • 更多用法參考 https://docs.python.org/2/library/collections.html#collections.defaultdict

Counter

  • Counter是一個簡單的計數(shù)器,幫助我們針對某項數(shù)據(jù)進行計數(shù)。
    In [1]: from collections import Counter
    In [2]: s = '''HangZhou lukou'''
    In [3]: c = Counter(s)
    In [4]: c
    Out[4]: 
    Counter({' ': 1,
            'H': 1,
            'Z': 1,
            'a': 1,
            'g': 1,
            'h': 1,
            'k': 1,
            'l': 1,
            'n': 1,
            'o': 2,
            'u': 3})
    In [5]: c.most_common(5)  #   出現(xiàn)次數(shù)最多的 5個字符
    Out[5]: [('u', 3), ('o', 2), ('a', 1), (' ', 1), ('g', 1)]   
    
  • 更多用法參考 https://docs.python.org/2/library/collections.html#collections.Counter

OrderedDict

  • Python中的 dict 是通過計算 key 的哈希值來確定存儲位置的,因此存在 dict 中的數(shù)據(jù)是無序的,當我們需要獲得一個有序的字典對象時,可以使用 OrderedDict, OrderedDict中的數(shù)據(jù)會按照插入的順序排序
    In [1]: from collections import OrderedDict
    In [2]: od = OrderedDict()
    In [3]: od['b'] = 1
    In [4]: od['a'] = 1
    In [5]: od['c'] = 1
    In [6]: od
    Out[6]: OrderedDict([('b', 1), ('a', 1), ('c', 1)])
    
    
  • 如果某個key對應的值改變了,順序不變。
    In [7]: od['a'] = 2
    In [8]: od
    Out[8]: OrderedDict([('b', 1), ('a', 2), ('c', 1)])
    
  • 在比較兩個OrderDict時,OrderedDict要內(nèi)容和順序完全相同才會視為相等。
  • 更多用法參考 https://docs.python.org/2/library/collections.html#collections.OrderedDict
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 常用模塊 認識模塊 什么是模塊 什么是模塊? 常見的場景:一個模塊就是一個包含了python定義和聲明的文件,文...
    go以恒閱讀 2,169評論 0 6
  • 簡介 collections包含了一些特殊的容器,針對Python內(nèi)置的容器,例如list、dict、set和tu...
    Boer223閱讀 13,700評論 0 11
  • 原文:http://python.jobbole.com/80847/ 在Python中有一些內(nèi)置的數(shù)據(jù)類型,比如...
    陽光小鎮(zhèn)少爺閱讀 803評論 0 1
  • The Python Data Model If you learned another object-orien...
    plutoese閱讀 1,953評論 0 51
  • 大膽去做不敢做的事,雖然膽怯,但做了就有收獲。當你變得不再膽怯,你就又成長了。每天看著別人的成功事跡,受到的只是一...
    黑白月光閱讀 273評論 0 1

友情鏈接更多精彩內(nèi)容