defaultdict 14-python -python3 base in ()

1.collections.defaultdict 类

from collections import defaultdict

 

2.collections.defaultdict class compared with the factory function dict:

(1) It is well known in Python dict If the access key does not exist in the dictionary, it will lead to KeyError exception. But sometimes, the dictionary there is a default value of each key is very convenient. defaultdict avoid KeyError exception.

 1 # 1-dict()
 2 strings = ('puppy', 'kitten', 'puppy', 'puppy',
 3    'weasel', 'puppy', 'kitten', 'puppy')
 4 counts = {}
 5 for kw in strings:
 6  counts[kw] += 1
 7 
 8 # 报错
 9 #Traceback (most recent call last):
10 # File "C:\Users\summer\Desktop\demo.py", line 5, in <module>
11 #    counts[kw] += 1
12 #KeyError: 'puppy'
13 
14 # 2-defaultdict()
15 from collections import defaultdict
16 
17 strings = ('puppy', 'kitten', 'puppy', 'puppy',
18    'weasel', 'puppy', 'kitten', 'puppy')
19 counts = defaultdict(int)
20 for kw in strings:
21  counts[kw] += 1
22 
23 print(counts)
24 
25 # defaultdict(<class 'int'>, {'puppy': 5, 'kitten': 2, 'weasel': 1})

 

(2) default_factory receiving a plant as a function of parameters like e.g. int str list set.

Defaultdict initialization function accepts a class type as a parameter, when the key is accessed does not exist, a value can be instantiated as Type Default factory default value is determined by the function.

from collections import defaultdict

dic1 = defaultdict(int)
print(dic1['a'])

dic2 = defaultdict(list)
print(dic2['a'])

dic3 = defaultdict(dict)
print(dic3['a'])

# 0
# []
# {}

 

(3) returns the function instance factory, then a corresponding method having a function of the plant.

 

Guess you like

Origin www.cnblogs.com/summer1019/p/11233783.html