您的位置:首页 > 编程语言 > Python开发

Python高级编程-如何统计序列中元素的出现频度?

2017-11-05 17:23 579 查看
>>> from random import randint
>>> data = [randint (0,20) for _ in range (30)]
>>> data
[0, 16, 15, 8, 2, 12, 1, 4, 7, 3, 9, 18, 11, 16, 5, 3, 19, 11, 18, 4, 9, 19, 2, 3, 7, 17, 1, 8, 9, 9]
>>> c =dict.fromkeys(data,0)
>>> c
{0: 0, 16: 0, 15: 0, 8: 0, 2: 0, 12: 0, 1: 0, 4: 0, 7: 0, 3: 0, 9: 0, 18: 0, 11: 0, 5: 0, 19: 0, 17: 0}
>>> for x in data:
c[x]+=1

>>>
>>> x
9
>>> c
{0: 1, 16: 2, 15: 1, 8: 2, 2: 2, 12: 1, 1: 2, 4: 2, 7: 2, 3: 3, 9: 4, 18: 2, 11: 2, 5: 1, 19: 2, 17: 1}
>>>
>>> from collections import Counter
>>> c2= Counter(data)
>>> c
{0: 1, 16: 2, 15: 1, 8: 2, 2: 2, 12: 1, 1: 2, 4: 2, 7: 2, 3: 3, 9: 4, 18: 2, 11: 2, 5: 1, 19: 2, 17: 1}
>>> c2[10]
0
>>> c2[20]
0
>>> c2.most_common (3)#出现频率最多的三个数
[(9, 4), (3, 3), (16, 2)]
>>> c2
Counter({9: 4, 3: 3, 16: 2, 8: 2, 2: 2, 1: 2, 4: 2, 7: 2, 18: 2, 11: 2, 19: 2, 0: 1, 15: 1, 12: 1, 5: 1, 17: 1})
import re
txt= open ('CodingStyle')#linux内核文字
C3=Counter(re.split('\W+',txt))#分割txt中的单词
C3
....
C3.most_common(10)#出现次数最多的十个数字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息