Python标准库中collections对集合类型的数据结构进行了非常多拓展操作。这些操作在我们使用集合的时候会带来非常多的便利。多看看非常有优点。

defaultdict是当中一个方法,就是给字典value元素加入默认类型,之前看到过可是没注意怎么使用,今天特地瞅了瞅。

首先是各大文章介绍的第一个样例:

import collections as coll

def default_factory():
return 'default value' d = coll.defaultdict(default_factory, foo='bar')
print 'd:',d
print 'foo=>', d['foo']
print 'foo=>', d['bar'] #key为'bar'的元素不存在。会有一个默认值

输出结果是这种:

d: defaultdict(<function default_factory at 0x022E6E70>, {'foo': 'bar'})
foo=> bar
foo=> default value

结论:这里能够看到,当我们取字典中一个没有的key的时候就会自己主动依据 default_factory生成一个value。类似于 d.get('bar','default value')

一个对照的样例:

假设一个字典中有个map的value是一个set。往这个set连续加入两个元素,使用原始的dict是这种

dict_set1 = {}
#假设不知道这个字段中key有没有。须要先推断
if 'key' not in dict_set1:
dict_set1['key'] = set()
dict_set1['key'].add('111')
dict_set1['key'].add('000')
print dict_set1

假设使用defaultdict就是这种

dict_set = coll.defaultdict(set)
dict_set['key'].add('000')
dict_set['key'].add('111')
print dict_set

优点就是不须要做set的初始化这个推断了。

两个使用的小案例

ss = '1111222233334444'
dict_int = coll.defaultdict(int)
for s in ss:
dict_int[s] += 1
print dict_int '''
官方文档的这个样例就能看到这样的写法的简洁了
https://docs.python.org/2/library/collections.html#collections.defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
'''

当我们做这样的带有统计性质的数据操作时候,这个对象非常好用。

本文出自 “orangleliu笔记本”博客,请务必保留此出处http://blog.csdn.net/orangleliu/article/details/38669867

[Python-tools]defaultdict的使用场景的更多相关文章

  1. python collections defaultdict

    class_counts  = defaultdict(int) 一.关于defaultdict 在Python里面有一个模块collections,解释是数据类型容器模块.这里面有一个collect ...

  2. Python tools for Visual Studio插件介绍

          Python tools for Visual Studio是一个免费开源的VisualStudio的插件,支持 VisualStudio 2010,2012与2013.我们想要实现的是: ...

  3. Seven Python Tools All Data Scientists Should Know How to Use

    Seven Python Tools All Data Scientists Should Know How to Use If you’re an aspiring data scientist, ...

  4. visual studio 2015使用python tools远程调试maya 2016

    步骤: 1. 去https://apps.exchange.autodesk.com/MAYA/en/Home/Index搜索Developer Kit并下载,maya 2016可以直接点击这里下载. ...

  5. Python Tools for Machine Learning

    Python Tools for Machine Learning Python is one of the best programming languages out there, with an ...

  6. Python collections.defaultdict 笔记

    其实defaultdict 就是一个字典,只不过python自动的为它的键赋了一个初始值.这也就是说,你不显示的为字典的键赋初值python不会报错,看下实际例子. 比如你想计算频率 frequenc ...

  7. 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', ...

  8. python中defaultdict的用法

    初识defaultdict 之前在使用字典的时候, 用的比较随意, 只是简单的使用dict. 然而这样在使用不存在的key的时候发生KeyError这样的一个报错, 这时候就该defaultdict登 ...

  9. 一文看懂python主要应用领域或应用场景

    Python简介 Python(英国发音:/ˈpaɪθən/美国发音:/ˈpaɪθɑːn/),是一种面向对象的解释型计算机程序设计语言,由荷兰人GuidovanRossum于1989年发明,第一个公开 ...

随机推荐

  1. Jenkins+GitHub+maven

    介绍: http://192.168.193.128:8115/jenkins/ 用户名:admin密码:admin电子邮箱:admin@admin.com root/12345678添加新用户: t ...

  2. 【Luogu】P2221高速公路(线段树乱搞)

    题目链接 这题……我从一开始就想歪了qwq. 为了缅怀逝去的一小时我就把我的30分暴力思路放上来. 首先我们观察枚举的区间.假设我们要枚举的范围是1~5之间的四条路,为了方便我们把它们叫做abcd. ...

  3. 动态方式破解apk进阶篇(IDA调试so源码)

    动态方式破解apk进阶篇(IDA调试so源码) 来源 https://blog.csdn.net/qq_21051503/article/details/74907449 下面就说关于在IDA中And ...

  4. LibreOJ2043 - 「CQOI2016」K 远点对

    Portal Description 给出平面上的\(n(n\leq10^5)\)个整点,求在欧几里得距离下第\(k\)远的点对之间的距离. Solution k-d树+堆. 用小根堆维护当前找到的第 ...

  5. POJ2594Treasure Exploration(最小路径覆盖,相交)

    Treasure Exploration Have you ever read any book about treasure exploration? Have you ever see any f ...

  6. Hadoop 3.1.0 在 Ubuntu 16.04 上安装时遇到的问题

    1.Hadoop 安装 pdsh localhost: Connection refused Hadoop安装过程中使用 $ sbin/start-dfs.sh 启动节点时,发生错误提示: pdsh@ ...

  7. es6总结(十一)--class & decorator

  8. 快充 IC BQ25896 的 input current monitor

    BQ25896 沒有顯示 input current 的 register, 但可以讀 ILIM pin 的 電壓 做計算求出 input current.

  9. UE3客户端服务器GamePlay框架

    客户端(当前玩家)与服务器对应关系图: 整体上看,UE3的GamePlay框架使用的是MVC架构 ① 橙色的Actor对象及橙色箭头相连的成员变量只会被同步给Owner客户端 Controller:控 ...

  10. 完美解决xhost +报错: unable to open display ""

    https://blog.csdn.net/wojiuguowei/article/details/79201845