字典get方法和setdesault方法,统计message中各元素的出现频次

#统计message中各元素的出现频次,并以字典的形式输出:
message= 'There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.'
#方法一:dict.setdefault(key, default=None) 有key获取值、没key设置 key:default。
count1={}
for i in message:
count1.setdefault(i,0) # 查询此次计数前此字母出现的次数,没有就添加key,值为0.
count1[i] = count1[i]+1 #更新次数(for每次遍历一个字母,故次数加一) .
#上面两段代码可简化为:count1[i]=count1.setdefault(i,0)+1
print('>>>',count1)

#方法二:
from collections import Counter
print('>>>',dict(Counter(message)))

#方法三:# get方法
# dict.get(key, default=None) 有key获取值、没key返回default。
count2={}
for i in message:
count2[i]=count2.get(i,0)+1
print('>>>',count2)
上一篇:通过libcurl实现https访问服务器


下一篇:sql存储过程基础知识