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
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)
for item in x:
d[item] += 1
print(x)
print(d)
使用collections模块的Counter类可以快速实现这个功能,并且提供更多的功能,例如查找出现次数最多的元素
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)
print(x)
print(d)
print(d.items())
print(d.most_common(1))
print(d.most_common(3))