@@ -6,7 +6,7 @@ collections 一个重要的 类 就是计数器,妈妈再也不用担心我不
6
6
7
7
小时候我们数数是这样数的
8
8
9
- ```
9
+ ``` python
10
10
# coding=utf-8
11
11
12
12
words = [' a' , ' b' , ' c' , ' b' , ' a' , ' a' , ' b' , ' c' ]
@@ -25,7 +25,7 @@ print cnt
25
25
26
26
现在我们可这样数数
27
27
28
- ```
28
+ ``` python
29
29
# coding=utf-8
30
30
31
31
words = [' a' , ' b' , ' c' , ' b' , ' a' , ' a' , ' b' , ' c' ]
@@ -43,7 +43,7 @@ print cnt.most_common(2)
43
43
44
44
其实使用原生列表也是可以的,像这样
45
45
46
- ```
46
+ ``` python
47
47
# coding=utf-8
48
48
49
49
words = [' a' , ' b' , ' c' , ' b' , ' a' , ' a' , ' b' , ' c' ]
@@ -59,7 +59,7 @@ print count
59
59
60
60
还可以使用其进行统计文件
61
61
62
- ```
62
+ ``` python
63
63
# coding=utf-8
64
64
65
65
@@ -71,13 +71,40 @@ print(line_count)
71
71
72
72
```
73
73
74
+ 2021-03-28
75
+
76
+ 一般在获取默认值的时候都比较烦,需要使用 ` .get ` 去获取。
77
+
78
+ 在对于默认是列表的字典,我们常用 ` defaultdict ` 去创建,那么对于默认为零的字典,就可以使用 ` Counter ` 去创建
79
+
80
+ ``` python
81
+ # -*- coding: utf-8 -*-
82
+
83
+ from collections import defaultdict, Counter
84
+
85
+
86
+ if __name__ == ' __main__' :
87
+ default_list = defaultdict(list )
88
+ default_list[" a" ].append(1 )
89
+ default_list[" a" ].append(2 )
90
+ default_list[" a" ].append(3 )
91
+ print (default_list)
92
+
93
+ default_zero = Counter()
94
+ default_zero[" b" ] += 1
95
+ default_zero[" b" ] += 2
96
+ default_zero[" b" ] += 3
97
+ print (default_zero)
98
+
99
+ ```
100
+
74
101
### 字典
75
102
76
103
一般的字典进行赋值操作时,需要先检查键是否存在,` defaultdict ` 则不需要
77
104
78
105
> 使用 defaultdict 的时候需注意,初始化的时候需要填入想要的值的类型。
79
106
80
- ```
107
+ ``` python
81
108
# coding=utf-8
82
109
83
110
from collections import defaultdict
@@ -111,7 +138,7 @@ some_dict['colours']['favourite'] = "yellow"
111
138
112
139
直接进行嵌套赋值
113
140
114
- ```
141
+ ``` python
115
142
import collections
116
143
tree = lambda : collections.defaultdict(tree)
117
144
some_dict = tree()
@@ -122,7 +149,7 @@ some_dict['colours']['favourite'] = "yellow"
122
149
123
150
在 Python 内置函数库 Queue 中已经提供了队列和栈, 在这里提供了双端队列 deque ,可以两边插入,两边取出。
124
151
125
- ```
152
+ ``` python
126
153
# coding=utf-8
127
154
128
155
from collections import deque
@@ -156,7 +183,7 @@ deque([4, 3, 1, 2])
156
183
157
184
还可以限制队列长度,超出长度的数据会被另一端挤出, 还可以进行队列的循环移位,左移或右移
158
185
159
- ```
186
+ ``` python
160
187
# coding=utf-8
161
188
162
189
from collections import deque
@@ -195,7 +222,7 @@ deque([6, 3, 2, 1, 0], maxlen=5)
195
222
196
223
字典是无序的,输入与输出的顺序都不一定一样, collections 中的 OrderedDict 能保证输出输入顺序绝对一致
197
224
198
- ```
225
+ ``` python
199
226
# coding=utf-8
200
227
201
228
from collections import OrderedDict
@@ -223,7 +250,7 @@ print o
223
250
224
251
namedtuple 是一个字典类型的元组,同样是不可变的,但是它又和字典一样存在键值对。
225
252
226
- ```
253
+ ``` python
227
254
# coding=utf-8
228
255
229
256
from collections import namedtuple
@@ -249,7 +276,7 @@ print perry._asdict
249
276
250
277
但是在 collections 库中,只有在 Python 3.4 及以上才能够使用 Enum 枚举类型
251
278
252
- ```
279
+ ``` python
253
280
# coding=utf-8
254
281
255
282
from collections import namedtuple
0 commit comments