python模块之collections

2020-01-19 16:40:40 浏览数 (1)

计数器 Counter

  • 计数元素迭代器 elements()
  • 计数对象拷贝 copy()
  • 计数对象清空 clear()
代码语言:javascript复制
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  (对字典的补充,可以记住字典元素添加的顺序)

代码语言:javascript复制
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,(指定字典值的类型)

代码语言:javascript复制
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 (给元组对应的值起个对应的名字,相当于字典)

代码语言:javascript复制
from collections import namedtuple

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

0 人点赞