失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Python collections 模块 namedtuple Counter defaultdict

Python collections 模块 namedtuple Counter defaultdict

时间:2021-05-02 17:52:06

相关推荐

Python 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]: FalseIn [10]: p[3] == t[3]Out[10]: False

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

In [1]: from collections import namedtupleIn [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.idOut[5]: '001'In [6]: p.id == t.idOut[6]: False

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

if img_result[5] == "car":# img_result[5] is car typeimg_display_type += 1if img_result[7] == "black": # img_result[7] is car colourimg_display_colour += 1if img_result[9] == 1:# img_result[9] is thief flagimg_display_thief += 1if img_result[10] == 1:img_display_orientation += 1if img_result[11] == 1:# img_result[11] is person flagimg_display_person += 1

2. Counter

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

In [18]: from collections import CounterIn [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]: 4In [24]: c.get('a')Out[24]: 4In [25]:

3. DefaultDict

DefaultDict能自动创建一个被初始化的字典,也就是每个键都已经被访问过一次。在实际开发中经常会写类似下面的代码,即判断一个键是否在字典中,如果不在则给该字典对应的键赋值空列表或者字典,如果在,则进行某种赋值等。

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]: dOut[41]: {'a': ['x'], 'b': [], 'c': []}

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

默认值为列表:

In [47]: from collections import defaultdictIn [48]: d = defaultdict(list)In [49]: d['a'].append('1')In [50]: dOut[50]: defaultdict(list, {'a': ['1']})In [51]: d['b'].append('2')In [52]: dOut[52]: defaultdict(list, {'a': ['1'], 'b': ['2']})

默认值为字典:

In [53]: from collections import defaultdictIn [54]: d = defaultdict(dict)In [55]: dOut[55]: defaultdict(dict, {})In [56]: d['a']['1'] = "a1"In [57]: dOut[57]: defaultdict(dict, {'a': {'1': 'a1'}})In [58]: d['b']['2'] = "b2"In [59]: dOut[59]: defaultdict(dict, {'a': {'1': 'a1'}, 'b': {'2': 'b2'}})

默认值为整型

In [60]: d = defaultdict(int)In [61]: dOut[61]: defaultdict(int, {})In [62]: d['a'] = 1In [63]: d['b'] = 2In [64]: dOut[64]: defaultdict(int, {'a': 1, 'b': 2})

如果觉得《Python collections 模块 namedtuple Counter defaultdict》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。