生成包含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)