Python collections

本文介绍了Python中常用的数据结构如Counter、deque、defaultdict等的应用,并详细讲解了如何进行元素计数、堆操作及默认字典的使用方法。同时,提供了关于列表、元组、字典等基础数据结构的高级应用实例。
#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)]

转载于:https://www.cnblogs.com/edisonxiang/p/4608389.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值