python模块之collections模块
生活随笔
收集整理的这篇文章主要介绍了
python模块之collections模块
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
计数器 Counter
-
计数元素迭代器 elements()
-
计数对象拷贝 copy()
-
计数对象清空 clear()
有序字典 OrderedDict (对字典的补充,可以记住字典元素添加的顺序)
from collections import OrderedDict order_dict = OrderedDict() print(order_dict,type(order_dict)) order_dict["c"] = 94 order_dict["b"] = 92 order_dict["d"] = 95 order_dict["a"] = 90 print(order_dict,type(order_dict)) #返回有序字典对象,OrderedDict([('c', 94), ('b', 92), ('d', 95), ('a', 90)]) <class 'collections.OrderedDict'> print(dict(order_dict),type(order_dict))#{'c': 94, 'b': 92, 'd': 95, 'a': 90} <class 'collections.OrderedDict'> print(list(order_dict),type(order_dict))#['c', 'b', 'd', 'a'] <class 'collections.OrderedDict'> print(order_dict.popitem()) #提取出字典的最后一个键值对 ('a', 90) print(order_dict) #OrderedDict([('c', 94), ('b', 92), ('d', 95)]) print(order_dict.pop("b")) #提取出字典指定键对应的值 print(order_dict) #OrderedDict([('c', 94), ('d', 95)]) order_dict.move_to_end("c") #将指定的键值对移动到最后 print(order_dict) #OrderedDict([('d', 95), ('c', 94)])默认字典 defaultdict,(指定字典值的类型)
from collections import defaultdictdefault_dict = defaultdict(list) # 指定字典的值类型为列表 print(default_dict,type(default_dict)) #defaultdict(<class 'list'>, {}) <class 'collections.defaultdict'>for i in range(10):default_dict["a"].append(i)print(default_dict) #defaultdict(<class 'list'>, {'a': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]})
可命名元组 namedtuple (给元组对应的值起个对应的名字,相当于字典)
from collections import namedtupletuple1 = namedtuple("tuple_name",["name","age","school","adress"]) print(tuple1) tuple1 = tuple1("xu",20,"jinggangshan","jiangxi") print(tuple1.name)
转载于:https://www.cnblogs.com/xuxianshen/p/10222707.html
总结
以上是生活随笔为你收集整理的python模块之collections模块的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【原】Coursera—Andrew N
- 下一篇: 第一个python命令