Python collections.defaultdict() 与 dict的使用和区别
看样子这个文档是难以看懂了。直接看示例:
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()) |
看看结果
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()比较相似
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 k in s: ... d[k] + = 1 ... >>> list (d.items()) [( 'i' , 4 ), ( 'p' , 2 ), ( 's' , 4 ), ( 'm' , 1 )] |
Python collections.defaultdict() 与 dict的使用和区别的更多相关文章
- (转)Python 3 collections.defaultdict() 与 dict的使用和区别
原文:https://www.cnblogs.com/herbert/archive/2013/01/09/2852843.html 在Python里面有一个模块collections,解释是数据类型 ...
- Python 3 collections.defaultdict() 与 dict的使用和区别
综述: 这里的defaultdict(function_factory)构建的是一个类似dictionary的对象,其中keys的值,自行确定赋值,但是values的类型,是function_fact ...
- python collections defaultdict
class_counts = defaultdict(int) 一.关于defaultdict 在Python里面有一个模块collections,解释是数据类型容器模块.这里面有一个collect ...
- Python collections.defaultdict 笔记
其实defaultdict 就是一个字典,只不过python自动的为它的键赋了一个初始值.这也就是说,你不显示的为字典的键赋初值python不会报错,看下实际例子. 比如你想计算频率 frequenc ...
- Python collections.OrderedDict解决dict元素顺序问题
编程中遇到个问题,python json.loads时元素顺序可能会发生变化. 这个对于一些需要使用元素顺序来做一些策略的代码来说是致命的. 在网上查了查,结合自己的知识总结一下. 使用dict时,K ...
- Python: dict setdault函数与collections.defaultdict()的区别
setdault用法 >>>dd={'hy':1,'hx':2} >>>cc=dd.setdefault('hz',1) >>>cc 返 ...
- python collections module's defaultdict
Collections is a high-performance container datatypes. defaultdict objects class collections.default ...
- python collections模块 之 defaultdict
defaultdict 是 dict 的子类,因此 defaultdict 也可被当成 dict 来使用,dict 支持的功能,defaultdict 基本都支持.但它与 dict 最大的区别在于,如 ...
- python中的list, dict, tuple以及collections模块的基本用法
1.关于list的一些基本用法 # 创建没有初值的列表 list1=[] # 创建有初值的列表 list2=['this','is','a','list'] # 创建给定长度但初值不确定的列表 lis ...
随机推荐
- winxp iis5中修改最大连接数及添加多个站点
winxp iis5中修改最大连接数及添加多个站点 最 近用asp做一些东西,需要用到iis,还需要用photoshop做一些图片.以前都是在win2003下面做,可是photoshop里面很多中文字 ...
- zf-关于查询机把index.jsp换成index_new.jsp页面之后把功能链接都改成新页面的简单方法
一开始我都是找action 然后一个一个的改 把onmousedown="goURL('index.jsp')" 改成 onmousedown="goURL('index ...
- 功能强大的HTML
HTML基本标签(一) 1.什么是HTML html:Hyper TextMakeup language:超文本标记语言 html:网页的“源码” 浏览器:“解释和执行”html源码的工具 2.网页的 ...
- linux下的安装百度云网盘
linux下的百度网盘 (2014-10-20 18:01:14) 标签: linux 百度网盘 网盘 百度 forlinux 分类: 技术博文 百度网盘说实话,其实我挺喜欢的,好处什么的,就不说了, ...
- Spring中引入其他配置文件
一.引入其他 模块XML 在Spring的配置文件,有时候为了分模块的更加清晰的进行相关实体类的配置. 比如现在有一个job-timer.xml的配置 <?xml version="1 ...
- 强制删除sql用户链接
SELECT 'alter system kill session '''||sid||','||serial#||''';' FROM v$session WHERE username='USER' ...
- base库插件---拖动
/** * Created by Administrator on 2014/6/5 0005. Base-drag 基于Base库的拖拽插件 tags为你要拖拽的元素参数, 数组形式传入 */ $( ...
- javascript的 replace() 方法的使用讲解
String.prototype.replace() The replace() method returns a new string with some or all matches of a p ...
- WEB在线预览PDF
这是我在博客园发表的第一篇文章.以后会陆续把在线预览其他格式文档的解决方案发表出来. 解决思路:把pdf转换成html显示. 在线预览pdf我暂时了解3种解决方案,欢迎大家补充. 方案一: 利用pdf ...
- javascript技巧大全套
事件源对象 event.srcElement.tagName event.srcElement.type 捕获释放 event.srcElement.setCapture(); event.srcE ...