Python collections模塊

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


1.    namedtuple   生成可以使用名字來訪問元素內容的tuple子類

2.    deque   雙端隊列,可以快速的從另外一側追加和推出對象

3.    Counter   計數器,主要用來計數

4.    OrderedDict   有序字典

5.    defaultdict   帶有默認值的字典

 

下面看看每種類型的用法:


__author__ = 'MrChen'
# Python version 3.4.1
# Module: collections

#Counter 對象
from collections import Counter
c = Counter('abcdabcaba')
print(c) # Counter({'a': 4, 'b': 3, 'c': 2, 'd': 1})
print(c.most_common(2)) # [('a', 4), ('b', 3)]

#deque 對象
from collections import deque
d = deque('python')
d.append('3')
d.appendleft('nice')
print(d) # deque(['nice', 'p', 'y', 't', 'h', 'o', 'n', '3'])
d.pop()
d.popleft()
print(d) # deque(['p', 'y', 't', 'h', 'o', 'n'])

#defaultdict 對象
from collections import defaultdict
dic = defaultdict(list)
dic['red'].append(5)
dic['blue'].append(3)
dic['yellow'].append(4)
dic['red'].append(8)
print(dic.items()) # dict_items([('red', [5, 8]), ('yellow', [4]), ('blue', [3])])

#namedtuple 對象
from collections import namedtuple
websites = [
    ('baidu', 'http://www.baidu.com', '李彥宏'),
    ('sina',  'http://www.sina.com' , '王志東'),
    ('wangyi','http://www.163.com'  , '丁磊')
]
Website = namedtuple('myWebsite',['name', 'url', 'ceo'])
for w in websites:
    w = Website._make(w)
    print(w)
'''輸出:
myWebsite(name='baidu', url='http://www.baidu.com', ceo='李彥宏')
myWebsite(name='sina', url='http://www.sina.com', ceo='王志東')
myWebsite(name='wangyi', url='http://www.163.com', ceo='丁磊')
'''

#OrderedDict 對象
from collections import OrderedDict
items = (('d',3),('b',4),('a',1),('e',5),('c',2))
regular_dict = dict(items)
ordered_dict = OrderedDict(items)
print(regular_dict)
# {'a': 1, 'c': 2, 'b': 4, 'd': 3, 'e': 5}
# 可見一般的dict內部是亂序的
print(ordered_dict)
# OrderedDict([('d', 3), ('b', 4), ('a', 1), ('e', 5), ('c', 2)])
# OrderedDict是按照原來的順序存儲的

#如果需要進行排序
ordered_dict = OrderedDict(sorted(ordered_dict.items(), key=lambda t:t[0]))
print(ordered_dict) # OrderedDict([('a', 1), ('b', 4), ('c', 2), ('d', 3), ('e', 5)])





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