日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python counter_教你Python的collections.Counter类型

發布時間:2023/12/15 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 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學習資料和路線,想要這些資料的都可以關注小編,并私信“01”領取。

總結

以上是生活随笔為你收集整理的python counter_教你Python的collections.Counter类型的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。