瞭解Python的collections.Counter型別

2020-11-23 21:01:59

欄目介紹Python的collections.Counter型別。

collections.Counter 型別可以用來給可雜湊的物件計數,或者是當成多重集合來使用 —— 多重集合就是集合裡的元素可以出現多次1。

collections.Counter 型別類似於其它程式語言中的 bags 或者 multisets2

(1)基本用法

counter = collections.Counter(['生物', '印記', '考古學家', '生物', '棗', '印記'])
logging.info('counter -> %s', counter)
counter.update(['化石', '果實', '棗', '生物'])
logging.info('counter -> %s', counter)
most = counter.most_common(2)
logging.info('most -> %s', most)

執行結果:

INFO - counter -> Counter({'生物': 2, '印記': 2, '考古學家': 1, '棗': 1})
INFO - counter -> Counter({'生物': 3, '印記': 2, '棗': 2, '考古學家': 1, '化石': 1, '果實': 1})
INFO - most -> [('生物', 3), ('印記', 2)]

範例程式中,首先使用 collections.Counter() 初始化 counter 物件,這時 counter 物件中就已經計算好當前的詞語出現次數;collections.Counter()入參為可迭代物件,比如這裡的列表。接著使用 update() 方法傳入新詞語列表,這時 counter 物件會更新計數器,進行累加計算;最後使用 counter 物件的 most_common() 方法列印出次數排名在前 2 名的詞語列表。

(2)集合運算

collections.Counter 型別還支援集合運算。

a = collections.Counter({'老虎': 3, '山羊': 1})
b = collections.Counter({'老虎': 1, '山羊': 3})
logging.info('a -> %s', a)
logging.info('b -> %s', b)
logging.info('a+b -> %s', a + b)
logging.info('a-b -> %s', a - b)
logging.info('a&b -> %s', a & b)
logging.info('a|b -> %s', a | b)

執行結果:

INFO - a -> Counter({'老虎': 3, '兔子': 2, '山羊': 1})
INFO - b -> Counter({'山羊': 3, '老虎': 1})
INFO - a+b -> Counter({'老虎': 4, '山羊': 4, '兔子': 2})
INFO - a-b -> Counter({'老虎': 2, '兔子': 2})
INFO - a&b -> Counter({'老虎': 1, '山羊': 1})
INFO - a|b -> Counter({'老虎': 3, '山羊': 3, '兔子': 2})
  • 範例中的 a 與 b 都是 Counter 型別物件。這裡還演示了 Counter 物件可以使用鍵值對的方式進行初始化操作;

  • a+b 表示並集操作,包含所有元素;

  • a-b 表示差集操作;

  • a&b 表示交集操作;

  • a|b 比較特殊,首先把所有的鍵囊括進來,然後比較兩個物件中的對應鍵的最大值,作為新物件的值。比如 a 物件中有 '老虎': 3,b 物件中有 '老虎': 1,那麼最後得到的物件是 '老虎': 3。

(3)正負值計數

Counter 型別中的計數器還支援負值。

c = collections.Counter(x=1, y=-1)
logging.info('+c -> %s', +c)
logging.info('-c -> %s', -c)

執行結果:

INFO - +c -> Counter({'x': 1})
INFO - -c -> Counter({'y': 1})

通過簡單的 +/- 作為 Counter 型別物件的字首,就可以實現正負計數過濾。Python 的這一設計很優雅。

相關免費學習推薦:

以上就是了解Python的collections.Counter型別的詳細內容,更多請關注TW511.COM其它相關文章!