生成包含1000个随机字符的字符串,然后统计每个字符出现的次数:
import string
import random
x=string.ascii_letters+string.digits #x是a-zA-Z-1-9
y="".join([random.choice(x) for i in range(1000)])#choice()用于从多个元素中随机选择一个
d=dict()#创建空字典
for ch in y:
d[ch]=d.get(ch,0)+1
for k, v in sorted(d.items()):
print(k,":",v)
import string,random,collections
x=string.ascii_letters+string.digits #x是a-zA-Z-1-9
y="".join([random.choice(x) for i in range(1000)])#choice()用于从多个元素中随机选择一个
count=collections.Counter(y)
print(count)
for k,v in sorted(count.items()):
print(k,":",v)