Python中陣列所有元素的頻率計數
在本教程中,我們將編寫一個程式來查詢陣列中所有元素的頻率。我們可以透過不同的方法找到它,讓我們探索其中的兩種。
使用字典
初始化陣列。
初始化一個空**字典**。
遍歷列表。
如果元素不在字典中,則將其值設定為**1**。
否則將值遞增**1**。
透過遍歷字典列印元素和頻率。
示例
讓我們看看程式碼。
# intializing the list
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# initializing dict to store frequency of each element
elements_count = {}
# iterating over the elements for frequency
for element in arr:
# checking whether it is in the dict or not
if element in elements_count:
# incerementing the count by 1
elements_count[element] += 1
else:
# setting the count to 1
elements_count[element] = 1
# printing the elements frequencies
for key, value in elements_count.items():
print(f"{key}: {value}")輸出
如果您執行上述程式,您將獲得以下結果。
1: 3 2: 4 3: 5
讓我們看看使用collections模組的Counter類的第二種方法。
使用Counter類
匯入**collections**模組。
初始化陣列。
將列表傳遞給**Counter**類。並將結果儲存在一個變數中。
透過遍歷結果列印元素和頻率。
示例
請看下面的程式碼。
# importing the collections module
import collections
# intializing the arr
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# getting the elements frequencies using Counter class
elements_count = collections.Counter(arr)
# printing the element and the frequency
for key, value in elements_count.items():
print(f"{key}: {value}")輸出
如果您執行上述程式碼,您將獲得與前一個相同的輸出。
1: 3 2: 4 3: 5
結論
如果您對本教程有任何疑問,請在評論部分提出。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP