Python练习(四)——字典的应用

1.给出一个字符串,在程序中赋初值为一个句子,例如“To improve is to change;to be perfect is to change often.”

需要:计算句子中各字符出现的频数(通过字典存储)

sentence = input("Please input a sentence:")
sentence_list = list(sentence)
sentence_1 = []
#列表字符去重后
for str_i in sentence:
    if str_i not in sentence_1:
        sentence_1.append(str_i)
chars = {}
for str_i in sentence_1:
    chars[str_i] = sentence_list.count(str_i)
print(chars)

猜你喜欢

转载自blog.csdn.net/weixin_41179709/article/details/81638451