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进行数据分析一书。