欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python模块之collections模块

程序员文章站 2022-04-27 20:52:06
计数器 Counter 计数元素迭代器 elements() 计数对象拷贝 copy() 计数对象清空 clear() 有序字典 OrderedDict (对字典的补充,可以记住字典元素添加的顺序) 默认字典 defaultdict,(指定字典值的类型) 可命名元组 namedtuple (给元组对 ......

计数器 counter

  • 计数元素迭代器 elements()
  • 计数对象拷贝 copy()
  • 计数对象清空 clear()
from collections import counter
#import collections
d = counter("abdadakdabfdj")  #对值计数,返回一个对象
print(d, type(d))               #counter({'a': 4, 'd': 4, 'b': 2, 'k': 1, 'f': 1, 'j': 1}) <class 'collections.counter'>
print(list(d), type(d))         #['a', 'b', 'd', 'k', 'f', 'j'] <class 'collections.counter'>
print(dict(d), type(d))         #{'a': 4, 'b': 2, 'd': 4, 'k': 1, 'f': 1, 'j': 1} <class 'collections.counter'>
print(d.elements())   #elements()方法返回一个迭代器,内容为进行计数的元素
for i in d.elements():
    print(i)       # a a a a d d d d b b k f j
d1 = d.copy()
print(d1,type(d1))       #counter({'a': 4, 'd': 4, 'b': 2, 'k': 1, 'f': 1, 'j': 1}) <class 'collections.counter'>
d2 = d.subtract("aaa")
print(d2,type(d2))
d3 = d.update('aaa')
print(d3,type(d3))
d4 = d.pop("j")
print(d4,d)   #  1    counter({'a': 4, 'd': 4, 'b': 2, 'k': 1, 'f': 1})
d.clear() # clear()方法清空计数的元素\
print(d)    #  counter()

有序字典 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 defaultdict

default_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 namedtuple

tuple1 = namedtuple("tuple_name",["name","age","school","adress"])
print(tuple1)
tuple1 = tuple1("xu",20,"jinggangshan","jiangxi")
print(tuple1.name)