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
- 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}})