python練習:計算出字符串中每個字符出現的次數


# 計算出以下字符串,每個字符出現的次數
a = "hello,world!"
print('a=',a)

#辦法1
print ("統計a中各項的個數,辦法1(字典):")
dicta = {}
for i in a:
    dicta[i] = a.count(i)
print (dicta)


# 辦法2
print ("統計a中各項的個數,辦法2(collections的counter):")
from collections import Counter
print(Counter(a))


# 辦法3
print ("統計a中各項的個數,辦法3(count方法):")
for i in a:
    print("%s:%d" %(i,a.count(i)))    #用count方法計算各項數量,簡單打印出來而已

# 辦法4(結果同3)
print ("統計a中各項的個數,辦法4(列表count方法):")
lista = list(a)                           #字符串轉為列表
print ('lista:',lista)
for i in lista:
    print("%s:%d" %(i,lista.count(i)))    #用列表的count方法計算各項數量

打印結果:

a= hello,world!
統計a中各項的個數,辦法1(字典):
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1}
統計a中各項的個數,辦法2(collections的counter):
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ',': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})
統計a中各項的個數,辦法3(count方法):
h:1
e:1
l:3
l:3
o:2
,:1
w:1
o:2
r:1
l:3
d:1
!:1
統計a中各項的個數,辦法4(列表count方法):
lista: ['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd', '!']
h:1
e:1
l:3
l:3
o:2
,:1
w:1
o:2
r:1
l:3
d:1
!:1

Process finished with exit code 0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM