一、基礎介紹
Python集合模塊collections.counter是Python的內置模塊之一,可以方便地統計字符出現的次數。首先我們需要導入collections模塊。
import collections
獲取字符串s中各字符出現的次數,可以使用下面一行代碼:
result = collections.Counter(s)
其中result是一個字典,key為各字符,value為出現的次數。
二、排序
我們可以使用sorted函數對result進行排序,可以按照字符出現的次數降序排列。
sorted_result = sorted(result.items(), key=lambda x: -x[1])
其中sorted_result是一個list,list中的每個元素也是一個tuple,tuple的第一個元素為字符,第二個元素為出現的次數。-x[1]表示按照第二個元素降序排序。
三、堆棧
collections.counter還可以用在堆棧中,可以方便地獲取堆棧中最常用的元素。
四、元素為0的不顯示
在使用collections.counter進行計數時,如果某個元素的數量為0,那麼它將不會顯示在counter的輸出中。
s = 'abcc' count = collections.Counter(s) count['d'] = 0 print(count)
輸出結果為:
Counter({'c': 2, 'a': 1, 'b': 1})
五、使用collections.counter統計單詞出現的次數
使用collections.counter統計單詞出現的次數,可以先將字符串分割成單詞,然後統計每個單詞出現的次數。
s = 'This is a test string. This string is used for testing.' words = s.split() word_count = collections.Counter(words) sorted_word_count = sorted(word_count.items(), key=lambda x: -x[1]) print(sorted_word_count)
輸出結果為:
[('This', 2), ('is', 2), ('string', 2), ('a', 1), ('test', 1), ('used', 1), ('for', 1), ('testing.', 1)]
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/186253.html