歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python collections模塊實例

Python collections模塊實例

日期:2017/3/1 9:35:45   编辑:Linux編程

Python作為一個“內置電池”的編程語言,標准庫裡面擁有非常多好用的模塊。

比如今天想給大家 介紹的 collections 就是一個非常好的例子

collections模塊基本介紹

Python擁有一些內置的數據類型,比如str, int, list, tuple, dict等, collections模塊在這些內置數據類型的基礎上,提供了幾個額外的數據類型:
1.namedtuple(): 生成可以使用名字來訪問元素內容的tuple子類
2.deque: 雙端隊列,可以快速的從另外一側追加和推出對象
3.Counter: 計數器,主要用來計數
4.OrderedDict: 有序字典
5.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'王志東'),
('linuxidc', 'http://www.linuxidc.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='linuxidc', url='http://www.linuxidc.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']})
參考資料
上面只是非常簡單的介紹了一下collections模塊的主要內容,主要目的就是當你碰到適合使用 它們的場所時,能夠記起並使用它們,起到事半功倍的效果。
如果要對它們有一個更全面和深入了解的話,還是建議閱讀官方文檔和模塊源碼。
https://docs.python.org/2/library/collections.html#module-collections

Python解析xml文檔實例 http://www.linuxidc.com/Linux/2012-02/54760.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved