为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Smart猫小萌 2021-07-16 18:14:09
我试图做以下练习:考虑句子“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())



查看完整回答
反对 回复 2021-07-28
  • 3 回答
  • 0 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号