from random import choices
from string import ascii_letters, digits
x =''.join(choices(ascii_letters+digits, k=10))
d =dict()# 创建空字典for ch in x:
d[ch]= d.get(ch,0)+1# x中有ch字符,个数+1,并作为字典的值print(x)print(d)
也可以使用collections模块的defaultdict类来实现
from random import choices
from string import ascii_letters, digits
from collections import defaultdict
x =''.join(choices(ascii_letters+digits, k=10))
d = defaultdict(int)# 字典的值全为int类型,当访问的键不存在的时候,0作为默认值for item in x:
d[item]+=1print(x)print(d)
from random import choices
from string import ascii_letters, digits
from collections import Counter
x =''.join(choices(ascii_letters+digits, k=10))
d = Counter(x)# 统计x中各种字符的个数print(x)print(d)print(d.items())# 转换成列表,以(键,值)作为元素print(d.most_common(1))# 出现次数最多的一个字符print(d.most_common(3))# 出现次数最多的3个字符