1-3如何统计序列元素出现的次数
2018-02-28 本文已影响5人
cuzz_
image.png
统计序列
image.pngPython 字典(Dictionary) fromkeys() 函数用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
from random import randint
from collections import Counter
data = [randint(0, 20) for _ in range(50)]
# 以data为key, 默认为0的字典
c = dict.fromkeys(data, 0)
for x in data:
c[x] += 1
c2 = Counter(data)
# 取出次数最多的3个
print(c2.most_common(3))
统计出现的单词数
from collections import Counter
import re
txt = open("quick_sort.py").read()
data = re.split("\W+", txt)
c = Counter(data)
print(c.most_common(2))