方法一、统计列表中每个元素出现的次数
def calculate_count():
from random import randint
data = [randint(0,3) for _ in xrange(6)]
print data # [1, 3, 3, 2, 2, 1]
c = dict.fromkeys(data,0) # {0: 0, 1: 0, 2: 0, 3: 0}
for x in data:
c[x]+=1
print c # {1: 2, 2: 2, 3: 2}
思考:找出来出现频度最高的元素及次数?
方法二、统计列表中每个元素出现的次数
def calculate_count2():
from collections import Counter
data = [1,2,2,2,3,3,5,6,6,6,6]
c = Counter(data)
print c # Counter({6: 4, 2: 3, 3: 2, 1: 1, 5: 1}),得到一个字典
print c[6] # 4
print c.most_common(2) # [(6, 4), (2, 3)],查找出现频度为前两个的
实战:找出一篇文章中出现次数最高的单词
def calculate_count3():
from collections import Counter
content = open('2.txt','r').read()
print content,type(content) # i love python , and you? if you love it too? <type 'str'>
import re
c = Counter(re.split('\W+',content))
print c # Counter({'love': 2, 'you': 2, 'and': 1, '': 1, 'i': 1, 'it': 1, 'python': 1, 'too': 1, 'if': 1})
num = c.most_common(1)
print num # [('love', 2)]
网友评论