defaultdict python_python中defaultdict的使用

1、class collections.defaultdict([default_factory[, ...]])

(1)上述命令返回一个类似于字典的新对象。

(2)defaultdict是内置dict类的子类。它重写一种方法并添加一个可写的实例变量。

直接举例子吧。

2、defaultdict Examples

(1)将default_factory设置为列表

from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

d = defaultdict(list)

for k, v in s:

d[k].append(v)

sorted(d.items())

输出结果为:

[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

可以看出,元组中的第一个元素是没有变化的,而第二个值则是根据第一个元素进行了聚类,所以使用列表的时候,它是具有聚类的效果的,返回格式为列表+元组。

官方解释如下:

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

dic.setdefault如下:

d = {}

for k, v in s:

d.setdefault(k, []).append(v)

print(d.items())

sorted(d.items())

输出结果为:

dict_items([('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])])

[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

其实从这里就可以看出defultdict(list)便捷性。

(2)将default_factory设置为整数

首次遇到键时,因为内部并没有任何的数值,所以default_factory会调用int来提供默认计数零。然后递增操作为每个字母建立计数。

s = 'mississippi'

d = defaultdict(int)

for k in s:

d[k] += 1

sorted(d.items())

输出结果为:

[('i', 4), ('m', 1), ('p', 2), ('s', 4)]

(3)将default_factory设置为集合

s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]

d = defaultdict(set)

for k, v in s:

d[k].add(v)

sorted(d.items())

输出结果为:

[('blue', {2, 4}), ('red', {1, 3})]

3、defaultdict总结

其实,从上面我们可以看得出来,defaultdict根据不同的设置形式,会略有差异。

(1)共同之处:

基本构成结构都是列表和元组形式。

(2)差异之处

在基本单元元组里,键值(第二个数据)的样式是不同的,比如列表,则用列表的形式,达到聚类目的。而整数则用整数的形式,计算出相同字符的个数。同样的,集合则用字典的方式,达到聚类的目的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值