(1)浅层认知
collections是python内建标准库的集合模块,功能十分强大。
defaultdict是模块中的默认字典对象。
(2)最初的目的
为什么叫默认字典,就是为了解决,当外部调取该字典某个不存在的键时,会根据当前字典元素类型,返回对应的空值。
- 例如,字典元素都是string,返回空值是"";
- 再比如,字典元素都是list,返回空值是[];
- 再比如,字典元素都是tuple,返回空值是();
- 再比如,字典元素都是set,返回空值是set();
(3)第一个参数:工厂函数类型
以此衍生出,给定默认字典的第1个参数,定义了这个新创建的字典元素到底是什么类型的。
- dict = collections.defaultdict(str)
- dict = collections.defaultdict(list)
- dict = collections.defaultdict(tuple)
- dict = collections.defaultdict(set)
(4)列表特性字典:同键整合,物以类聚,保留每个元素(列表强调个体)
【使用场景】快速合并元组对列表
请注意,这里使用的是列表的append方法,就是即便元素相同也记录。
>>> old = [('yellow', 2), ('blue', 4), ('yellow', 1), ('blue', 1), ('red', 2)]
>>> new = defaultdict(list)
>>> for key, value in old:
new[key].append(value)
>>> new.items()
dict_items([('yellow', [2, 1]), ('blue', [4, 1]), ('red', [2])])
>>> sorted(new.items())
[('blue', [4, 1]), ('red', [2]), ('yellow', [2, 1])]
(5)集合特性字典:同键整合,相同元素合并(集合强调集体)
【使用场景】快速合并集合对字典
请注意,当前键值对的增加是使用的集合方法add,即只记录不同值,相同值不记录。
>>> colors = [('yellow', 2), ('blue', 4), ('yellow', 1), ('blue', 4), ('yellow', 2)]
>>> color_set = defaultdict(set)
>>> for key, value in colors:
color_set[key].add(value)
>>> color_set.items()
dict_items([('yellow', {1, 2}), ('blue', {4})])
>>> sorted(color_set.items())
[('blue', {4}), ('yellow', {1, 2})]
(6)计数巧用
(6-1)数字特性字典:可对字符串字母键整合计数(数字就是加和,无论整浮)
【使用场景】int类型的合并是加和
>>> string = 'nobugshahaha'
>>> count = defaultdict(int)
>>> for key in string:
count[key] += 1
>>> count.items()
dict_items([('n', 1), ('o', 1), ('b', 1), ('u', 1), ('g', 1), ('s', 1), ('h', 3), ('a', 3)])
>>> sorted(count.items())
[('a', 3), ('b', 1), ('g', 1), ('h', 3), ('n', 1), ('o', 1), ('s', 1), ('u', 1)]
(6-2)计数实际可用集合模块的另一个对象:Counter
专业的计数器,直接对字符串字母计数。
from collections import Counter
>>> count2 = Counter(string)
>>> count2
Counter({'h': 3, 'a': 3, 'n': 1, 'o': 1, 'b': 1, 'u': 1, 'g': 1, 's': 1})
>>> count2.items()
dict_items([('n', 1), ('o', 1), ('b', 1), ('u', 1), ('g', 1), ('s', 1), ('h', 3), ('a', 3)])
>>> count2.most_common()
[('h', 3), ('a', 3), ('n', 1), ('o', 1), ('b', 1), ('u', 1), ('g', 1), ('s', 1)]