天天看點

Python3 如何統計序列中元素出現的頻率

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from random import randint

data = [randint(0, 20) for _ in range(30)]
           

1. 疊代

'''第一種方法'''
# 先将清單轉化為字典,重複的鍵保留一個,初始化值為0
d = {}
for i in data:
    d[i] = 0

# 也可以使用字典 fromkeys() 函數
# 以序列 seq 中元素做字典的鍵,value 為字典所有鍵對應的初始值
# d = dict.fromkeys(data, 0)

# 初始化完成後再對清單進行疊代,當出現一個重複的鍵對其加1
for i in data:
    d[i] += 1
print(d)
    
'''第二種方法'''
# 使用字典 get() 函數傳回指定鍵的值,如果值不在字典中傳回預設值
d2 = {}
for i in data:
    d2[i] = d2.get(i, 0) + 1
print(d2)
           

2. 使用标準庫中的

collections.Counter

統計元素出現的頻率

from collections import Counter

d3 = Counter(data)

print(dict(d3))
# most_common(3) 是取出頻率最高的3個元素
print(d3.most_common(3))
           

運作結果:

Geek-Mac:Downloads zhangyi$ python3 Nice.py 
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
[(10, 4), (1, 4), (5, 3)]