Python 列表中出現頻率最高的元素
許多統計資料分析試圖找到給定值列表中頻率最高的那些值。Python 提供多種方法,我們可以使用這些方法從給定列表中找到這樣的值。以下是這些方法。
使用 Counter
collections 模組中的 Counter 函式提供了一個選項,可以直接找到給定列表中最常見的元素。我們有 most_common 函式,我們可以為其傳遞引數 1 以獲取頻率最高的單個元素,如果我們需要頻率最高的兩個元素,則傳遞 2。
示例
from collections import Counter
# Given list
listA = ['Mon', 'Tue','Mon', 9, 3, 3]
print("Given list : ",listA)
# Adding another element for each element
Newlist1 = Counter(listA).most_common(1)
Newlist2 = Counter(listA).most_common(2)
# Results
print("New list after duplication: ",Newlist1)
print("New list after duplication: ",Newlist2)輸出
執行以上程式碼將得到以下結果:
Given list : ['Mon', 'Tue', 'Mon', 9, 3, 3]
New list after duplication: [('Mon', 2)]
New list after duplication: [('Mon', 2), (3, 2)]使用 mode
mode 是 Python 的 statistics 模組中提供的統計函式。它將輸出頻率最高的元素。如果有多個這樣的元素,則首先遇到的頻率最高的元素將是輸出。
示例
from statistics import mode
# Given list
listA = ['Mon', 'Tue','Mon', 9, 3, 3]
listB = [3,3,'Mon', 'Tue','Mon', 9]
print("Given listA : ",listA)
print("Given listB : ",listB)
# Adding another element for each element
Newlist1 = mode(listA)
Newlist2 = mode(listB)
# Results
print("New listA after duplication: ",Newlist1)
print("New listB after duplication: ",Newlist2)輸出
執行以上程式碼將得到以下結果:
Given listA : ['Mon', 'Tue', 'Mon', 9, 3, 3] Given listB : [3, 3, 'Mon', 'Tue', 'Mon', 9] New listA after duplication: Mon New listB after duplication: 3
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP