看样子这个文档是难以看懂了。直接看示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import collections
= [('yellow'1), ('blue'2), ('yellow'3), ('blue'4), ('red'1)]
# defaultdict
= collections.defaultdict(list)
for k, v in s:
    d[k].append(v)
# Use dict and setdefault   
= {}
for k, v in s:
    g.setdefault(k, []).append(v)
      
# Use dict
= {}
for k, v in s:
    e[k] = v
##list(d.items())
##list(g.items())
##list(e.items())

看看结果

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', [24]), ('red', [1]), ('yellow', [13])]
>>> list(g.items())
[('blue', [24]), ('red', [1]), ('yellow', [13])]
>>> list(e.items())
[('blue'4), ('red'1), ('yellow'3)]
>>> d
defaultdict(<class 'list'>, {'blue': [24], 'red': [1], 'yellow': [13]})
>>> g
{'blue': [24], 'red': [1], 'yellow': [13]}
>>> e
{'blue'4'red'1'yellow'3}
>>> d.items()
dict_items([('blue', [24]), ('red', [1]), ('yellow', [13])])
>>> d["blue"]
[24]
>>> d.keys()
dict_keys(['blue''red''yellow'])
>>> d.default_factory
<class 'list'>
>>> d.values()
dict_values([[24], [1], [13]])

可以看出

collections.defaultdict(list)使用起来效果和运用dict.setdefault()比较相似

python help上也这么说了

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():

说这种方法会和dict.setdefault()等价,但是要更快。

有必要看看dict.setdefault()

setdefault(key[, default])

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 in s:
...     d[k] += 1
...
>>> list(d.items())
[('i'4), ('p'2), ('s'4), ('m'1)]

最新文章

  1. winfrom 隐藏任务栏(win7)
  2. php : 基础(6)
  3. 多线程完成socket
  4. Java编程中“为了性能”尽量要做到的一些地方
  5. sublime3 常用插件
  6. 基于 ANSIBLE 自动化运维实践
  7. 浩瀚先森(guohao1206.com)
  8. Js对象转String的函数 和 JSON转String
  9. 1047 - Neighbor House(简单线性DP)
  10. HDOJ(HDU) 2504 又见GCD(利用最大公约数反推)
  11. [Google Code Jam (Qualification Round 2014) ] B. Cookie Clicker Alpha
  12. net异步编程之await
  13. perl学习(8) 控制:unless,until,next,redo,last
  14. Kotlin初探
  15. tar+pigz+ssh实现大数据压缩传输
  16. [js高手之路] html5 canvas系列教程 - 线条样式(lineWidth,lineCap,lineJoin,setLineDash)
  17. window 7 安装Jmeter并配置https录制脚本
  18. VMware端口映射配置步骤
  19. Unity 5 使用Roslyn编译器支持C# 7
  20. python网络爬虫day1

热门文章

  1. 快速部署Python应用:Nginx+uWSGI配置详解
  2. jquery给img添加按钮事件
  3. Android面试经验1
  4. WINCE下进程间通信(二)
  5. DWR整合之Servlet
  6. CodeForces 591B Rebranding
  7. SpringMvc MultipartFile 图片文件上传
  8. CentOS新增开机启动项
  9. 谈谈java的BlockingQueue
  10. Windows Server 2012 在个人终端上使用的推荐设置