Python中元素頻率統計
在本文中,我們將學習如何查詢Python列表中元素的頻率。我們可以透過不同的方法解決這個問題。讓我們看看其中的兩種方法。
按照以下步驟編寫程式碼。
- 用元素和一個空字典初始化列表。
- 迭代元素列表。
- 檢查元素是否已存在於字典中。
- 如果元素已存在於字典中,則增加其計數。
- 如果元素不存在於字典中,則將其計數初始化為1。
- 列印字典。
示例
讓我們看看程式碼。
# initializing the list random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B'] frequency = {} # iterating over the list for item in random_list: # checking the element in dictionary if item in frequency: # incrementing the counr frequency[item] += 1 else: # initializing the count frequency[item] = 1 # printing the frequency print(frequency)
如果執行以上程式碼,則會得到以下結果。
輸出
{'A': 3, 'B': 3, 'C': 1, 'D': 2}
按照以下步驟以另一種方式解決問題。我們將使用模組方法來查詢元素的頻率。
- 匯入collections模組。
- 用元素初始化列表。
- 使用collections模組中的Counter獲取元素的頻率。
- 使用dict()將結果轉換為字典並列印頻率。
示例
讓我們看看程式碼。
# importing the module import collections # initializing the list random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B'] # using Counter to find frequency of elements frequency = collections.Counter(random_list) # printing the frequency print(dict(frequency)) {'A': 3, 'B': 3, 'C': 1, 'D': 2}
如果執行以上程式碼,則會得到以下結果。
輸出
{'A': 3, 'B': 3, 'C': 1, 'D': 2}
結論
如果您對本文有任何疑問,請在評論區提出。
廣告