模块-->collections

collections模块

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。

1.namedtuple: 生成可以使用名字来访问元素内容的tuple

2.deque: 双端队列,可以快速的从另外一侧追加和推出对象

3.Counter: 计数器,主要用来计数

4.OrderedDict: 有序字典

5.defaultdict: 带有默认值的字典

  • namedtuple    命名元祖

from collections import namedtuple   
t = namedtuple('time_tupel',['','','','','','',''])
t1 = t(18,1,12,13,14,56,897)
print(t1)
print(t1.年)

Counter   计数

s = ['a','b','c']
dic = {}
for i in s:
    dic[i] = dic.get(i,0) + 1
print(dic)
结果:
{'a': 1, 'b': 1, 'c': 1}
  
计算元素个数,结果以字典的形式显示



from collections import Counter
s = ['a','b','c']
c = Counter(s)
print(c)
结果:Counter({'a': 1, 'b': 1, 'c': 1})
 

猜你喜欢

转载自www.cnblogs.com/wangxiaoshou/p/10293107.html