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

来源:互联网 发布:知呼和分答 编辑:程序博客网 时间:2024/06/14 23:35
>>> 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    >>>>>> x9>>> 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)]>>> c2Counter({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 retxt= open ('CodingStyle')#linux内核文字C3=Counter(re.split('\W+',txt))#分割txt中的单词C3....C3.most_common(10)#出现次数最多的十个数字

阅读全文
0 0
原创粉丝点击