Python容器數據類型——collections


#!/usr/bin/python
#coding=utf-8
#http://docs.python.org/library/collections.html

#count對象 Only 2.7
from collections import Counter
#統計字母出現的次數
Counter('hello world')  
Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])

 #小於等於0的會被忽略
c = Counter(a=4, b=2, c=0, d=-2)
list(c.elements())
#取前三個最多的字母
Counter('hello world').most_common(3) 

#
from collections import deque
d = deque('abc')
d.append('d')
d.pop() #后入先出
d.popleft() #先入先出

#返回最后n行文本
deque(open(filename), n)

#defaultdict
from collections import defaultdict
#使用list初始化一個dict
d = defaultdict(list)
d["yellow"].append(1)
d["red"].append(2)
d["yellow"].append(3)

print d.items() #[('red', [2]), ('yellow', [1, 3])]
#用int初始華一個dict
d = defaultdict(int)
d["yellow"] += 1
d["red"] += 2
d["yellow"] += 3
print d.items() #[('red', 2), ('yellow', 4)]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM