Ak的Python系列筆記01_統計字符串出現次數(字典setdefault()方法)

//來源--《Python編程快速上手》

1.字典:略

2.字典setdefault()方法:

    傳遞給該方法的第一個參數,是要檢查的鍵;第二個參數,如果要檢查的

鍵不存在,方法就會返回鍵的值。


3.計算一個字符串中每個字符出現 的次數

message='Today is 2018.7.11,sunny!'
count={}
for Character in message:
     count.setdefault(Character,0)
     count[Character]=count[Character]+1
print(count)

#輸出
{'T': 1, 'o': 1, 'd': 1, 'a': 1, 'y': 2, ' ': 2, 'i': 1, 's': 2, '2': 1, '0': 1, '1': 3, '8': 1, '.': 2, '7': 1, ',': 1, 'u': 1, 'n': 2, '!': 1}

    程序循環迭代message中的每個字符,setdefault()方法調用確保了鍵存在於count

字典中(默認值是0),這樣在執行count[Character]=count[Character]+1時,

就不會拋出KeyError錯誤。

4.整整齊齊輸出

    首行添加該行代碼  import pprint

    最後一行改爲:pprint.pprint(count)     或者改爲   print(pprint.pformat(count))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章