看樣子這個文檔是難以看懂了。直接看示例:python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
collections
s
=
[(
'yellow'
,
1
), (
'blue'
,
2
), (
'yellow'
,
3
), (
'blue'
,
4
), (
'red'
,
1
)]
# defaultdict
d
=
collections.defaultdict(
list
)
for
k, v
in
s:
d[k].append(v)
# Use dict and setdefault
g
=
{}
for
k, v
in
s:
g.setdefault(k, []).append(v)
# Use dict
e
=
{}
for
k, v
in
s:
e[k]
=
v
##list(d.items())
##list(g.items())
##list(e.items())
|
看看結果app
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
list
(d.items())
[(
'blue'
, [
2
,
4
]), (
'red'
, [
1
]), (
'yellow'
, [
1
,
3
])]
>>>
list
(g.items())
[(
'blue'
, [
2
,
4
]), (
'red'
, [
1
]), (
'yellow'
, [
1
,
3
])]
>>>
list
(e.items())
[(
'blue'
,
4
), (
'red'
,
1
), (
'yellow'
,
3
)]
>>> d
defaultdict(<
class
'list'
>, {
'blue'
: [
2
,
4
],
'red'
: [
1
],
'yellow'
: [
1
,
3
]})
>>> g
{
'blue'
: [
2
,
4
],
'red'
: [
1
],
'yellow'
: [
1
,
3
]}
>>> e
{
'blue'
:
4
,
'red'
:
1
,
'yellow'
:
3
}
>>> d.items()
dict_items([(
'blue'
, [
2
,
4
]), (
'red'
, [
1
]), (
'yellow'
, [
1
,
3
])])
>>> d[
"blue"
]
[
2
,
4
]
>>> d.keys()
dict_keys([
'blue'
,
'red'
,
'yellow'
])
>>> d.default_factory
<
class
'list'
>
>>> d.values()
dict_values([[
2
,
4
], [
1
], [
1
,
3
]])
|
能夠看出函數
collections.defaultdict(list)使用起來效果和運用dict.setdefault()比較類似ui
python help上也這麼說了spa
When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():code
說這種方法會和dict.setdefault()等價,可是要更快。orm
有必要看看dict.setdefault()ip
setdefault(key[, default])ci
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.文檔
若是這個key已經在dictionary裏面存着,返回value.若是key不存在,插入key和一個default value,返回Default. 默認的defaults是None.
可是這裏要注意的是defaultdict是和dict.setdefault等價,和下面那個直接賦值是有區別的。從結果裏面就能夠看到,直接賦值會覆蓋。
從最後的d.values還有d[「blue」]來看,後面的使用實際上是和dict的用法同樣的,惟一不一樣的就是初始化的問題。defaultdict能夠利用工廠函數,給初始keyi帶來一個默認值。
這個默認值也許是空的list[] defaultdict(list), 也許是0, defaultdict(int).
再看看下面的這個例子。
defaultdict(int) 這裏的d實際上是生成了一個默認爲0的帶key的數據字典。你能夠想象成 d[key] = int default (int工廠函數的默認值爲0)
d[k]因此能夠直接讀取 d[「m」] += 1 就是d[「m」] 就是默認值 0+1 = 1
後面的道理就同樣了。
1
2
3
4
5
6
7
|
>>> s
=
'mississippi'
>>> d
=
defaultdict(
int
)
>>>
for
k
in
s:
... d[k]
+
=
1
...
>>>
list
(d.items())
[(
'i'
,
4
), (
'p'
,
2
), (
's'
,
4
), (
'm'
,
1
)]
|