Python collections模塊--Counter

https://docs.python.org/2/library/collections.html

collectionsPython內(nèi)建的一個(gè)高性能容器數(shù)據(jù)類(lèi)型,提供了許多有用的集合類(lèi)。

  • namedtuple() :生成可以使用名字來(lái)訪問(wèn)元素內(nèi)容的tuple子類(lèi)
  • deque: 雙端隊(duì)列,可以快速的從另外一側(cè)追加和推出對(duì)象
  • Counter: 計(jì)數(shù)器,主要用來(lái)計(jì)數(shù)
  • OrderedDict: 有序字典
  • defaultdict: 帶有默認(rèn)值的字典

Counter 計(jì)數(shù)器

  • 列表重復(fù)元素的計(jì)數(shù)
In [3]: import collections

# 列表重復(fù)元素的計(jì)數(shù)
In [4]: c1 = collections.Counter('aaabbbsssdc')
In [5]: print c1
Counter({'a': 3, 's': 3, 'b': 3, 'c': 1, 'd': 1})

# 空的計(jì)數(shù)器
In [44]: c = collections.Counter()

In [45]: c
Out[45]: Counter()
# 通過(guò)映射關(guān)系生成的計(jì)數(shù)器
In [46]: c = collections.Counter({'red': 4, 'blue': 2})

In [47]: c
Out[47]: Counter({'blue': 2, 'red': 4})
# 通過(guò)關(guān)鍵字生成的計(jì)數(shù)器
In [48]: c = collections.Counter(cats=4, dogs=8)

In [49]: c
Out[49]: Counter({'cats': 4, 'dogs': 8})

  • most_common(n) -- 列出最多的前n項(xiàng)
In [13]: c1.most_common(3)
Out[13]: [('a', 3), ('s', 3), ('b', 3)]
  • elements() -- 以迭代器的方式取數(shù)據(jù),如果某個(gè)元素的計(jì)數(shù)是負(fù)值,則忽略
# elements() -- 以迭代器的方式取數(shù)據(jù),如果某個(gè)元素的計(jì)數(shù)是負(fù)值,則忽略
In [20]: c3 = collections.Counter(a=3, b=3, c=0, d=-2)

In [21]: c3.elements()
Out[21]: <itertools.chain at 0x109127610>

In [22]: list(c3.elements())
Out[22]: ['a', 'a', 'a', 'b', 'b', 'b']

  • subtract -- 從可迭代或從另一映射(或計(jì)數(shù)器)中減去元素
# subtract -- 從可迭代或從另一映射(或計(jì)數(shù)器)中減去元素
In [25]: c = collections.Counter(a=4, b=2, c=0, d=-2)

In [26]: d = collections.Counter(a=1, b=2, c=3, d=4)

In [27]: c.subtract(d)

In [28]: c
Out[28]: Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

  • update -- 和 subtract 相反,元素相加
# update -- 和 subtract 相反,元素相加
In [29]: c = collections.Counter(a=4, b=2, c=0, d=-2)

In [30]: d = collections.Counter(a=1, b=2, c=3, d=4)

In [31]: c.update(d)

In [32]: c
Out[32]: Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2})

  • clear -- 清除
In [33]: c1
Out[33]: Counter({'a': 3, 'b': 3, 'c': 1, 'd': 1, 's': 3})

In [34]: c1.clear()

In [35]: c1
Out[35]: Counter()
  • 字典重復(fù)Key的計(jì)數(shù)
# 字典重復(fù)Key的計(jì)數(shù)
In [8]: dic1 = {
   ...:     'a': 1,
   ...:     'b': 2,
   ...:     'a': 1,
   ...:     'a': 3}
In [10]: c2 = collections.Counter(dic1)
In [11]: print c2
Counter({'a': 3, 'b': 2})
In [12]: c2['a']
Out[12]: 3
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容