国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python collections模塊實例講解

2019-11-25 18:27:38
字體:
來源:轉載
供稿:網友

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'王志東'),
    ('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']})

參考資料

上面只是非常簡單的介紹了一下collections模塊的主要內容,主要目的就是當你碰到適合使用 它們的場所時,能夠記起并使用它們,起到事半功倍的效果。

如果要對它們有一個更全面和深入了解的話,還是建議閱讀官方文檔和模塊源碼。

https://docs.python.org/2/library/collections.html#module-collections

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 三穗县| 阆中市| 射阳县| 五常市| 海伦市| 屯留县| 濮阳市| 涪陵区| 东安县| 星座| 诸城市| 师宗县| 乌恰县| 汾阳市| 称多县| 武鸣县| 利辛县| 丰台区| 固原市| 信阳市| 延边| 大田县| 昭觉县| 巴林左旗| 龙海市| 神农架林区| 广东省| 夹江县| 嘉黎县| 巧家县| 秦安县| 林周县| 磐安县| 垣曲县| 陵水| 东辽县| 靖安县| 陆丰市| 马关县| 民乐县| 古丈县|