python | Collections 包的几个常见用法

简介

之前都没很在意过collections这个模块,以为有很多复杂的功能,所以只考虑了defaultdict一个用法。没想到今天做力扣的时候,看官方解答中Counter也是属于collections模块,这么看这个还是很不错的。
写个总结,以备以后快速检索。

PS:发现这个博客写的很详细啊,有不懂的可以去看看:Python常用数据结构之collections模块

总结

Counter

从名称就能看出来,Counter是计数器,可以对字符串,列表,字典实现计数功能。

示例程序:

from collections import Counter

str = "abcbcaccbbad"
li = ["a","b","c","a","b","b"]
d = {"1":3, "3":2, "17":2}

#Counter获取各元素的个数,返回字典
print ("Counter(s):", Counter(str))
print ("Counter(li):", Counter(li))
print ("Counter(d):", Counter(d))

输出为:

>>>> Counter(s): Counter({'b': 4, 'c': 4, 'a': 3, 'd': 1})
>>>> Counter(li): Counter({'b': 3, 'a': 2, 'c': 1})
>>>> Counter(d): Counter({'1': 3, '3': 2, '17': 2})

defaultdict

详见:python | defaultdict用法详解

from collections import defaultdict

dict1 = defaultdict(int)
dict2 = defaultdict(set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
dict1[2] ='two'

print(dict1[1])
print(dict2[1])
print(dict3[1])
print(dict4[1])


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值