collections.defaultdict

python 简单数据分析

collections. 这个模块提供容器相关的更高性能的数据类型,它们提供比通用容器 dict, list, set 和tuple更强大的功能。

**collections.defaultdict:
一个dict的子类,可以使创建的字典具有默认值

文档:
defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.

somedict = {}
print(somedict[3]) # KeyError

someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0

Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a “default” item, it calls the function object that you pass in the constructor (more precisely, it’s an arbitrary “callable” object, which includes function and type objects). For the first example, default items are created using int(), which will return the integer object 0. For the second example, default items are created using list(), which returns a new empty list object.

也就是说, 如果我用defaultdict创建字典,可以指定默认值,但默认值必须是可调用对象(函数对象),如list,int等。例如:

from collections import defaultdict
res2 = defaultdict(int) #默认值为0
defaultdict([]) #默认值为list
defaultdict(lambda:999) #默认值为999

还可以用自定义函数来代替lambda
此外,dict中的setdefault函数和此有共通之处,都可以指定默认值

部分参考如下:
作者: MrSu
出处:https://www.cnblogs.com/suguangti/p/13150567.html
版权:本站使用「CC BY 4.0」创作共享协议,转载请在文章明显位置注明作者及出处。

此外还有部分参考使用Python进行数据分析一书。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值