1. 程式人生 > >python之獲取list中元素出現的次數

python之獲取list中元素出現的次數

迅速獲取list中元素出現的次數
from collections import Counter
def counter(arr):
    return Counter(arr).most_common(1)      # 返回出現頻率最高的一個數
  

例如:
from collections import Counter

arr = [1,2,3,1,2,3,4,1,1]
def counter(arr):
    return Counter(arr).most_common(1)
print(counter(arr))

返回結果:[(1, 4)]  括號第一個數 是頻率最高的數 第二個數是 出現次數

可以在 return Counter(arr).most_common(1)[0][0] 獲取到 出現頻率最高的數