特殊的字典----cookbook读书笔记

来源:互联网 发布:scp linux tftp 编辑:程序博客网 时间:2024/05/22 11:50

1. 使用collections 模块中的defaultdict 来实现一个键对应多个值的字典

一键对多个值,只支持两种多值list和set,其它操作都类似

>>> from collections import defaultdict>>> d = defaultdict(list)>>> d['a'].append(1)>>> d['a'].append('ok')>>> d['b'].append(2)>>> d['a'].append(3)>>> ddefaultdict(<class 'list'>, {'a': [1, 'ok', 3], 'b': [2]})>>> s = defaultdict(set)>>> s['a'].add(1)>>> s['a'].add(2)>>> s['b'].add('ok')>>> s['b'].add(3)>>> sdefaultdict(<class 'set'>, {'a': {1, 2}, 'b': {3, 'ok'}})

2. 使用collections 模块中的OrderedDict 类控制一个字典中元素的顺序

>>> from collections import OrderedDict>>> d = OrderedDict()>>> d['a'] = 1>>> d['b'] = 'ok'>>> d['c'] = 3>>> d['e'] = 4>>> dOrderedDict([('a', 1), ('b', 'ok'), ('c', 3), ('e', 4)])>>> d['b'] = 2>>> dOrderedDict([('a', 1), ('b', 2), ('c', 3), ('e', 4)])

3. 使用collections.Counter 类对序列进行统计

Counter自动生成一个统计字典:
字典key为被统计元素,字典value为统计数量;
most_common(n)函数可以统计出最多的前n项;
Counter 生成的字典支持加减运算。

>>> from collections import Counter>>> words = [... 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',... 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',... 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',... 'my', 'eyes', "you're", 'under'... ]>>> word_counts = Counter(words)>>> top_three = word_counts.most_common(3)>>> top_three[('eyes', 8), ('the', 5), ('look', 4)]>>> word_counts['not']1>>> morewords = ['why','are','you','not','looking','in','my','eyes']>>> b = Counter(morewords)>>> word_counts-bCounter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2, "don't": 1, "you're": 1, 'under': 1})

原创粉丝点击