Python 笔记(09)— collections 模块 namedtuple、counter、defaultdict

1. namedtuple

假设有两个列表,如下,要判断两个列表中的某一个索引值是否相等。

In [7]: p = ['001', 'wohu', '100', 'Shaanxi']

In [8]: t = ['002', 'tom', '20', 'Beijing']

In [9]: p[0] == t[0]
Out[9]: False

In [10]: p[3] == t[3]
Out[10]: False

这样的话代码中会存在很多用于取值的索引值,导致代码的可读性并不太好,而 collections 模块的 namedtuple 很好的解决了这个问题。

In [1]: from collections import namedtuple

In [2]: person = namedtuple("Person", ['id', 'name', 'age', 'address'])

In [3]: p = person('001', 'wohu', '100', 'Shaanxi')

In [4]: t = person('002', 'tom', '20', 'Beijing')

In [5]: p.id
Out[5]: '001'

In [6]: p.id == t.id
Out[6]: False

联系之前自己写的代码,完全可以用这个替代,而且可读性还比较好。

if img_result[5] == "car":      # img_result[5] is car type
    img_display_type += 1

if img_result[7] == "black":    # img_result[7] is car colour
    img_display_colour += 1

if img_result[9] == 1:      	# img_result[9] is thief flag
    img_display_thief += 1

if img_result[10] == 1:
    img_display_orientation += 1

if img_result[11] == 1:     	# img_result[11] is person flag
    img_display_person += 1

2. counter

counter 正如名字那样,它的主要功能就是计数。

In [18]: from collections import Counter

In [19]: s = "abcdefabcdaba"

In [20]: c = Counter(s)

In [21]: c.most_common()	# 统计每个字符出现的次数
Out[21]: [('a', 4), ('b', 3), ('c', 2), ('d', 2), ('e', 1), ('f', 1)]

In [22]: sorted(c)	# 对字符按照出现次数由多到少排序
Out[22]: ['a', 'b', 'c', 'd', 'e', 'f']

In [23]: c['a']		# 获取每个字符出现的次数
Out[23]: 4

In [24]: c.get('a')
Out[24]: 4

In [25]: 

3. defauldict

defauldict 能自动创建一个被初始化的字典,也就是每个键都已经被访问过一次。

在实际开发中经常会写类似下面的代码,即判断一个键是否在字典中,如果不在则给该字典对应的键赋值空列表或者字典,如果在,则进行某种赋值等。

In [38]: d = {}

In [39]: k = ['a','b', 'c', 'a']

In [40]: for i in k:
    ...:     if i not in d:
    ...:         d[i] = []
    ...:     else:
    ...:         d[i].append('x')
    ...:         

In [41]: d
Out[41]: {'a': ['x'], 'b': [], 'c': []}

有了 defaultdict 就可以省略这个 if-else 分支,代码如下:

3.1 默认值为列表

In [47]: from collections import defaultdict

In [48]: d = defaultdict(list)

In [49]: d['a'].append('1')

In [50]: d
Out[50]: defaultdict(list, {'a': ['1']})

In [51]: d['b'].append('2')

In [52]: d
Out[52]: defaultdict(list, {'a': ['1'], 'b': ['2']})

3.2 默认值为字典

In [53]: from collections import defaultdict

In [54]: d = defaultdict(dict)

In [55]: d
Out[55]: defaultdict(dict, {})

In [56]: d['a']['1'] = "a1"

In [57]: d
Out[57]: defaultdict(dict, {'a': {'1': 'a1'}})

In [58]: d['b']['2'] = "b2"

In [59]: d
Out[59]: defaultdict(dict, {'a': {'1': 'a1'}, 'b': {'2': 'b2'}})

3.3 默认值为整型

In [60]: d = defaultdict(int)

In [61]: d
Out[61]: defaultdict(int, {})

In [62]: d['a'] = 1

In [63]: d['b'] = 2

In [64]: d
Out[64]: defaultdict(int, {'a': 1, 'b': 2})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wohu007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值