def count_each_char_1(string):
res = {}
for i in string:
if i not in res:
res[i] = 1
else:
res[i] += 1
return res
print(count_each_char_1('aenabsascd'))
方法二
def count_each_char_2(string):
res = {}
for i in string:
res[i] = res.get(i,0)+1
return res
print(count_each_char_2('aenabsascd'))
需要对出现的字母按从大到小排序
import operator
def count_each_char_sort_value(string):
res = {}
for i in string:
res[i] = res.get(i,0)+1
res = sorted(res.items(),key = operator.itemgetter(1),reverse = True)
return res
print(count_each_char_sort_value('aenabsascd'))