编程语言
首页 > 编程语言> > leetcode刷题 76题 python计数 Counter和defaultdict的区别

leetcode刷题 76题 python计数 Counter和defaultdict的区别

作者:互联网

[Python技巧]是时候用 defaultdict 和 Counter 代替 dictionary 了

https://blog.csdn.net/lc013/article/details/91813812

参考自这篇csdn博客

Counter和defaultdict都是collections类中的方法。

Counter和defaultdict的最主要的区别是,Counter是计数器,存储的数据只能是整数,而defaultdict

 

既然 Counter 这么好用,是不是只需要 Counter 就可以了?答案当然是否定的,因为 Counter 的问题就是其数值必须是整数,本身就是用于统计数量,因此如果我们需要的数值是字符串,列表或者元组,那么就不能继续用它。

这个时候,defaultdict 就派上用场了。它相比于 dict 的最大区别就是可以设置默认的数值,即便 key 不存在。例子如下:

输入

s = [('color', 'blue'), ('color', 'orange'), ('color', 'yellow'), ('fruit', 'banana'), ('fruit', 'orange'),
('fruit', 'banana')]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
print(d)
输出结果

defaultdict(<class 'set'>, {'color': {'blue', 'yellow', 'orange'}, 'fruit': {'banana', 'orange'}})

标签:defaultdict,python,Counter,color,fruit,orange,banana
来源: https://www.cnblogs.com/someonezero/p/16344152.html