首頁  >  文章  >  後端開發  >  了解Python的collections.Counter類型

了解Python的collections.Counter類型

coldplay.xixi
coldplay.xixi轉載
2020-11-23 17:36:293320瀏覽

python影片教學專欄介紹Python的collections.Counter類型。

了解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影片教學

以上是了解Python的collections.Counter類型的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.im。如有侵權,請聯絡admin@php.cn刪除