python学习笔记——统计序列中元素的出现频度


方法一:用字典方法统计序列中元素的出现频度

ange(30)] ##创建一个随机数序列
data
Out[57]: 
[5,
 13,
 0,
 1,
 17,
 8,
 7,
 3,
 19,
 15,
 19,
 15,
 11,
 17,
 16,
 12,
 9,
 17,
 4,
 0,
 17,
 4,
 1,
 14,
 2,
 2,
 6,
 12,
 3,
 2]
c = dict.fromkeys(data,0) ##创建一个字典,用随机数序列做键,默认初始值为0
c
Out[59]: 
{0: 0,
 1: 0,
 2: 0,
 3: 0,
 4: 0,
 5: 0,
 6: 0,
 7: 0,
 8: 0,
 9: 0,
 11: 0,
 12: 0,
 13: 0,
 14: 0,
 15: 0,
 16: 0,
 17: 0,
 19: 0}
for x in data: ##遍历建,如果键相同,就加1.就可以得出序列中元素出现的次数
    c[x] +=1
    
c
Out[61]: 
{0: 2,
 1: 2,
 2: 3,
 3: 2,
 4: 2,
 5: 1,
 6: 1,
 7: 1,
 8: 1,
 9: 1,
 11: 1,
 12: 2,
 13: 1,
 14: 1,
 15: 2,
 16: 1,
 17: 4,
 19: 2}
方法二:使用collection.Counter对象

Counter是一个简单的计数器,例如,统计字符出现的个数:

代码接方法一

from collections import Counter
c2 = Counter(data)
c2
Out[64]: 
Counter({0: 2,
         1: 2,
         2: 3,
         3: 2,
         4: 2,
         5: 1,
         6: 1,
         7: 1,
         8: 1,
         9: 1,
         11: 1,
         12: 2,
         13: 1,
         14: 1,
         15: 2,
         16: 1,
         17: 4,
         19: 2})
c2.most_common(3)##most_common 方法筛选频率最高的3个
Out[65]: 
[(17, 4), (2, 3), (0, 2)]



你可能感兴趣的:(Python)