统计序列中相同元素出现的频率最高的三个
-
以序列值为键,0为值的字典,通过遍历序列来对0进行加 速度:
***
推荐:***
data = [randint(1, 20) for _ in range(30)] d = dict.fromkeys(data, 0) for i in data: # 遍历序列 d[i] += 1 # 如果序列的值和字典的键相同,重复一次 from collections import Counter res = Counter(d) res.most_common(3) # 统计最高的三个
对英文文章单词进行频率最高10个词的统计
-
直接使用 collections 里面的 Counter方法 速度:
*****
推荐:*****
from collections import Counter text = open(r'english.txt', encoding="utf-8").read() data = re.split(r'\W+', text) res = Counter(data) res.most_common(10) # 统计出频率出现最高的 10 个 [('you', 32), ('to', 19), ('who', 10), ('those', 9), ('the', 8), ('and', 7), ('have', 7), ('that', 6), ('want', 6), ('make', 6)]