Python模塊: collections學習

轉載自:http://www.zlovezl.cn/articles/collections-in-python/

閱讀官方文檔和模塊源碼:https://docs.python.org/2/library/collections.html#module-collections


基本介紹

我們都知道,Python擁有一些內置的數據類型,比如str, int, list, tuple, dict等, collections模塊在這些內置數據類型的基礎上,提供了幾個額外的數據類型:

  • namedtuple(): 生成可以使用名字來訪問元素內容的tuple子類
  • deque: 雙端隊列,可以快速的從另外一側追加和推出對象
  • Counter: 計數器,主要用來計數
  • OrderedDict: 有序字典
  • defaultdict: 帶有默認值的字典

namedtuple()

namedtuple主要用來產生可以使用名稱來訪問元素的數據對象,通常用來增強代碼的可讀性, 在訪問一些tuple類型的數據時尤其好用。

舉個栗子

# -*- coding: utf-8 -*-
"""
比如我們用戶擁有一個這樣的數據結構,每一個對象是擁有三個元素的tuple。
使用namedtuple方法就可以方便的通過tuple來生成可讀性更高也更好用的數據結構。
"""
from collections import namedtuple

websites = [
    ('Sohu', 'http://www.google.com/', u'張朝陽'),
    ('Sina', 'http://www.sina.com.cn/', u'王志東'),
    ('163', 'http://www.163.com/', u'丁磊')
]

Website = namedtuple('Website', ['name', 'url', 'founder'])

for website in websites:
    website = Website._make(website)
    print website


# Result:
Website(name='Sohu', url='http://www.google.com/', founder=u'\u5f20\u671d\u9633')
Website(name='Sina', url='http://www.sina.com.cn/', founder=u'\u738b\u5fd7\u4e1c')
Website(name='163', url='http://www.163.com/', founder=u'\u4e01\u78ca')

deque

deque其實是 double-ended queue 的縮寫,翻譯過來就是雙端隊列,它最大的好處就是實現了從隊列 頭部快速增加和取出對象: .popleft().appendleft() 。

你可能會說,原生的list也可以從頭部添加和取出對象啊?就像這樣:

l.insert(0, v)
l.pop(0)

但是值得注意的是,list對象的這兩種用法的時間複雜度是 O(n) ,也就是說隨着元素數量的增加耗時呈 線性上升。而使用deque對象則是 O(1) 的複雜度,所以當你的代碼有這樣的需求的時候, 一定要記得使用deque。

作爲一個雙端隊列,deque還提供了一些其他的好用方法,比如 rotate 等。

舉個栗子

# -*- coding: utf-8 -*-
"""
下面這個是一個有趣的例子,主要使用了deque的rotate方法來實現了一個無限循環
的加載動畫
"""
import sys
import time
from collections import deque

fancy_loading = deque('>--------------------')

while True:
    print '\r%s' % ''.join(fancy_loading),
    fancy_loading.rotate(1)
    sys.stdout.flush()
    time.sleep(0.08)

# Result:

# 一個無盡循環的跑馬燈
------------->-------

Counter

計數器是一個非常常用的功能需求,collections也貼心的爲你提供了這個功能。

舉個栗子

# -*- coding: utf-8 -*-
"""
下面這個例子就是使用Counter模塊統計一段句子裏面所有字符出現次數
"""
from collections import Counter

s = '''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''.lower()

c = Counter(s)
# 獲取出現頻率最高的5個字符
print c.most_common(5)


# Result:
[(' ', 54), ('e', 32), ('s', 25), ('a', 24), ('t', 24)]

OrderedDict

在Python中,dict這個數據結構由於hash的特性,是無序的,這在有的時候會給我們帶來一些麻煩, 幸運的是,collections模塊爲我們提供了OrderedDict,當你要獲得一個有序的字典對象時,用它就對了。

舉個栗子

# -*- coding: utf-8 -*-
from collections import OrderedDict

items = (
    ('A', 1),
    ('B', 2),
    ('C', 3)
)

regular_dict = dict(items)
ordered_dict = OrderedDict(items)

print 'Regular Dict:'
for k, v in regular_dict.items():
    print k, v

print 'Ordered Dict:'
for k, v in ordered_dict.items():
    print k, v


# Result:
Regular Dict:
A 1
C 3
B 2
Ordered Dict:
A 1
B 2
C 3

defaultdict

我們都知道,在使用Python原生的數據結構dict的時候,如果用 d[key] 這樣的方式訪問, 當指定的key不存在時,是會拋出KeyError異常的。

但是,如果使用defaultdict,只要你傳入一個默認的工廠方法,那麼請求一個不存在的key時, 便會調用這個工廠方法使用其結果來作爲這個key的默認值。

# -*- coding: utf-8 -*-
from collections import defaultdict

members = [
    # Age, name
    ['male', 'John'],
    ['male', 'Jack'],
    ['female', 'Lily'],
    ['male', 'Pony'],
    ['female', 'Lucy'],
]

result = defaultdict(list)
for sex, name in members:
    result[sex].append(name)

print result

# Result:
defaultdict(<type 'list'>, {'male': ['John', 'Jack', 'Pony'], 'female': ['Lily', 'Lucy']})

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