python中的collections模块

collections模块干嘛用的?

答:除python提供的内置数据类型(int、float、str、list、tuple、dict)外,collections模块还提供了其他数据类型,使用如下功能需先导入collections模块(import collections)

可以理解为这些内置数据类型的另外一个升级版本的模块。

  • 计数器(counter)
  • 有序字典(orderedDict)
  • 默认字典(defaultdict)
  • 可命名元组(namedtuple)
  • 双向队列(deque)

一.计数器(Counter)计算元素的个数并且以字典的形式返回(元素:元素的个数)

1.Counter:返回值为迭代器

1 >>> import collections
2 >>> str = "aaabbbbbbccxxdd"
3 >>> collections.Counter(str)
4 Counter({'b': 6, 'a': 3, 'x': 2, 'c': 2, 'd': 2})

2.elements-迭代器:返回一个迭代其呀unsu被重复多少次,在迭代其中就被包含多少个此元素,所有元素按照字母排列。

1 >>> import collections
2 >>> str = "aaabbbbbbccxxdd"
3 >>> collections.Counter(str)//此时是一个迭代器,然后我们赋值给a
4 Counter({'b': 6, 'a': 3, 'x': 2, 'c': 2, 'd': 2})
5 >>> a = collections.Counter(str)//此时a就是一个迭代器
6 >>> a
7 Counter({'b': 6, 'a': 3, 'x': 2, 'c': 2, 'd': 2})
8 >>> a.most_common(3)//只取前面三个
9 [('b', 6), ('a', 3), ('x', 2)]

3.update:增加重复的次数

4.subtract:减少元素重复次数

原文地址:https://www.cnblogs.com/nul1/p/9030565.html