在 Python 的字典中分别计算大写和小写

我试图做以下练习:考虑句子“Jim 很快意识到漂亮的礼服很贵”。创建一个字典 count_letters ,键由句子中的每个唯一字母组成,值由每个字母在这句话中的使用次数组成。在字典中分别计算大写和小写字母。


下面是我的代码,我认为它正在做练习所要求的,但出于某种原因,它仍然说我没有做对。任何想法,任何人?


sentence = 'Jim quickly realized that the beautiful gowns are expensive'

count_letters = {}

cnt_lowercase = 0

cnt_uppercase = 0

#write your code here!

for c in sentence:

    if c.islower():

        if (c in count_letters) == False:

            count_letters[c]={c:sentence.count(c)}

            cnt_lowercase += 1

    if c.isupper():

        if (c in count_letters) == False:

            count_letters[c]={c:sentence.count(c)}

            cnt_uppercase += 1

print(str(cnt_lowercase))

print(str(cnt_uppercase))

print(count_letters)


Smart猫小萌
浏览 172回答 3
3回答

慕标琳琳

from collections import Countercount_letters = Counter('Jim quickly realized that the beautiful gowns are expensive')# this gives a dictionary of character -> count# if you need to skip spaces/punctuations (you probably do), use thiscount_letters = Counter(c for c in 'Jim quickly realized that the beautiful gowns are expensive' if c.isalpha())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python