首页 > 编程语言 > 详细

Python collections

时间:2015-06-29 22:04:58      阅读:350      评论:0      收藏:0      [点我收藏+]
#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)]

Python collections

原文:http://www.cnblogs.com/edisonxiang/p/4608389.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!