Python拥有一些内置的数据类型,比如str,int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型:
1. namedtuple 生成可以使用名字来访问元素内容的tuple子类
2. deque 双端队列,可以快速的从另外一侧追加和推出对象
3. Counter 计数器,主要用来计数
4. OrderedDict 有序字典
5. defaultdict 带有默认值的字典
下面看看每种类型的用法:
- __author__ = 'MrChen'
-
-
-
-
- from collections import Counter
- c = Counter('abcdabcaba')
- print(c)
- print(c.most_common(2))
-
-
- from collections import deque
- d = deque('python')
- d.append('3')
- d.appendleft('nice')
- print(d)
- d.pop()
- d.popleft()
- print(d)
-
-
- from collections import defaultdict
- dic = defaultdict(list)
- dic['red'].append(5)
- dic['blue'].append(3)
- dic['yellow'].append(4)
- dic['red'].append(8)
- print(dic.items())
-
-
- from collections import namedtuple
- websites = [
- ('baidu', 'http://www.baidu.com', '李彦宏'),
- ('sina', 'http://www.sina.com' , '王志东'),
- ('wangyi','http://www.163.com' , '丁磊')
- ]
- Website = namedtuple('myWebsite',['name', 'url', 'ceo'])
- for w in websites:
- w = Website._make(w)
- print(w)
- ''
-
-
-
-
-
-
- from collections import OrderedDict
- items = (('d',3),('b',4),('a',1),('e',5),('c',2))
- regular_dict = dict(items)
- ordered_dict = OrderedDict(items)
- print(regular_dict)
-
-
- print(ordered_dict)
-
-
-
-
- ordered_dict = OrderedDict(sorted(ordered_dict.items(), key=lambda t:t[0]))
- print(ordered_dict)