python常用数据结构模块--collections
import collections ''' python常用数据结构模块--collections collections是日常工作中的重点、高频模块,常用类型有: 计数器(Counter) 双向队列(deque) 参考源码 就是list 默认字典(defaultdict) 有序字典(OrderedDict) 可命名元组(namedtuple) #常用于定义一个类,该类只有一些属性,没有方法 ''' # namedtuple 用于定义一个类,该类只有一些属性,没有方法 People = collections.namedtuple("Peole", ["name", "age"]) people = People("W", 18) print(people) """ "C:\Program Files (x86)\python3.8\python.exe" D:/xiaoxiao/wzg/untitled/collection模块学习.py Peole(name='W', age=18) Process finished with exit code 0 """ # OrderedDict 有序字典 可实现按key或者value排序 print("正经的字典,") d = {} d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' for k, v in d.items(): print(k, v) print("不正经的字典(我有序了,哎,就是玩儿)") d1 = collections.OrderedDict() d1['a'] = 'A' d1['b'] = 'B' d1['c'] = 'C' d1['1'] = '1' d1['2'] = '2' for k, v in d1.items(): print(k, v) """ 输出: 正经的字典, 无序 a A b B c C 不正经的字典(我有序了,哎,就是玩儿) a A b B c C 1 1 2 2 """ print("正经的字典,") d2 = {} d2['a'] = 'A' d2['b'] = 'B' d2['c'] = 'C' d3 = {} d3['c'] = 'C' d3['a'] = 'A' d3['b'] = 'B' print("不正经的字典(我有序了,哎,就是玩儿)") d4 = collections.OrderedDict() d4['a'] = 'A' d4['b'] = 'B' d4['c'] = 'C' d5 = collections.OrderedDict() d5['c'] = 'C' d5['a'] = 'A' d5['b'] = 'B' print(d == d2) print(d4 == d5) """ 输出: True False 结论:有序的字典(OrderedDict):顺序不同的,元素相同,对象也是不同的 """ dd = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} #按key排序 kd = collections.OrderedDict(sorted(dd.items(), key=lambda item: item[0])) print(kd) #按照value排序 vd = collections.OrderedDict(sorted(dd.items(),key=lambda item:item[1])) print(vd) ''' 输出: OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) ''' #Counter 参考源码样例