我试图做以下练习:考虑句子“Jim 很快意识到漂亮的礼服很贵”。创建一个字典 count_letters ,键由句子中的每个唯一字母组成,值由每个字母在这句话中的使用次数组成。在字典中分别计算大写和小写字母。下面是我的代码,我认为它正在做练习所要求的,但出于某种原因,它仍然说我没有做对。任何想法,任何人?sentence = 'Jim quickly realized that the beautiful gowns are expensive'count_letters = {}cnt_lowercase = 0cnt_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 += 1print(str(cnt_lowercase))print(str(cnt_uppercase))print(count_letters)
3 回答

慕标琳琳
TA贡献1830条经验 获得超9个赞
from collections import Counter
count_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 this
count_letters = Counter(c for c in 'Jim quickly realized that the beautiful gowns are expensive' if c.isalpha())
添加回答
举报
0/150
提交
取消