Counter 与 defaultdict


Counter,defaultdict

最近写代码,觉得还是要用博客记录一下比较好,这样以后查找起来也方便,今天就先写Counter函数和defaultdict函数:

  • Counter
  • defaultdict

Counter()

Counter()函数用于计算元素出现的值以及次数,例如:

@requires_authorization
from collection import Counter
a = [6,4,1,2,2,3,1,1,4,5,3,2]
Counter(a)
>>> Counter({1: 3, 2: 3, 3: 2, 4: 2, 5: 1, 6: 1})

len(a)
>>>6

a.values()
>>>dict_values([1, 2, 3, 3, 2, 1])

总的来说,Counter对计算元素个数十分方便

defaultdict()

defaultdict()函数与普通的dict()函数不同之处:在于defaultdict()函数可以处理缺失键值,而dict()函数只能处理有键值的情况。
本篇博文对defaultdict()的理解源自:
https://blog.csdn.net/the_little_fairy___/article/details/80551538

  1. defaultdict()用于处理missing key的例子
    defaultdict()在dict()的基础上添加了一个missing(key)的方法,在调用一个不存在的key的时候,defaultdict函数会调用“missing”,返回一个int,set,list,dict对应的默认数值,不会出现KeyError的情况。
    int,set,dict,list的默认值分别是:0,set(),{},[]。
b = defaultdict(int)
b["a"]
>>>0
a = dict()
a["a"]
>>>KeyError: 'a'

2.dict.items()
在这里顺便提一下dict.items(),dict.items()用于遍历字典中的元素。
在字典的遍历的时候,不允许出现相同的键值,如果出现相同的键值会返还最后出现相同键值的元素

s = {'red': 1, 'blue': 2, 'red': 3, 'blue': 4, 'red': 1, 'blue': 4}
d = defaultdict(set)
for k in s:
    print(k)
    print(s[k])

>>>red
>>>1
>>>blue
>>>4
s = {'red': 1, 'blue': 2, 'red': 3, 'blue': 4, 'red': 1, 'blue': 4}
d = defaultdict(set)
for k,v in s.items():
    print(k)  #k为键值
    print(v)  #v为value

>>>red
>>>1
>>>blue
>>>4

要想解决这个问题,需要用元组的方法对字典进行保存

s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
#像这种形式的只能是元组形成的列表,如果是dict()字典,是不能存在相同的键
d = defaultdict(set)
for k, v in s:
  d[k].add(v)

print(d)
>>>defaultdict(<class 'set'>, {'red': {1, 3}, 'blue': {2, 4}})
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值