要求:
統(tǒng)計字符串中,各個字符串的個數(shù),并將其結(jié)果使用字典存儲;
比如:"hello world"字符串統(tǒng)計結(jié)果為:{'r': 1, 'w': 1, 'l': 3, 'o': 2, 'h': 1, 'd': 1, 'e': 1}
代碼實現(xiàn):
def count_char(test_str):
"""統(tǒng)計字符串的個數(shù)"""
count_dict = {} # 存儲統(tǒng)計結(jié)果的字典
for k in set(test_str):
if k == " ":
continue
count_dict[k] = test_str.count(k)
return count_dict
test_str = "hello world"
count_dict = count_char(test_str)
print(count_dict)
打印結(jié)果:{'o': 2, 'l': 3, 'r': 1, 'w': 1, 'd': 1, 'e': 1, 'h': 1}
代碼實現(xiàn)思路:
使用集合(set)去重的特性獲取單個字符串;
使用字符串的count方法統(tǒng)計字符串個數(shù);
代碼優(yōu)化:字典推導(dǎo)式簡化代碼:
def count_char(test_str):
"""統(tǒng)計字符串的個數(shù)"""
return {k: test_str.count(k) for k in set(test_str) if k not in " "}
test_str = "hello world"
count_dict = count_char(test_str)
print(count_dict)
其它實現(xiàn)方式:使用collections模塊的Counter方法,簡潔高效
import collections
test_str = "hello world"
count_dict = dict(collections.Counter(test_str))
print(count_dict)
打印結(jié)果:{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
最后編輯于 :2018.06.25 22:22:32
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者 平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。