Python.习题六 字典与集合(下)

Python.<习题六> 字典与集合

11.编写程序,对用户输入的英文字符串中各字母出现的次数进行统计(不区分大写字母和小写字母),统计结果使用字典存放。例如,字符串"I have 2 ideas."的统计结果为{“i”:2,“h”:1,“a”:2,“v”:1,“e”:2,“d”:1,“s”:1}。假设用户输入的字符串中可能包含字母以外的其他字符。

s=input("请输入字符串:")
myDict={
   }
for c in s:
    ch=c.lower()
    if ch.isalpha():
        myDict [ch]= myDict.get(ch,0)+1
print(myDict) 

在这里插入图片描述
12.已知字符串变量s=“When in the course of human events,it becomes necessary for one people to dissolve the political bands which have connected them with another,and to assume among the powers of the earth,the separate and equal atation to which the Laws of Nature and of Nature’s God entitle them,a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.”,存放了美国独立宣言中的一段话。试编写程序,实现以下功能:
(1)对文本中每个单词出现的次数进行统计,并将结果输出。
(2)输出出现次数排在前五名的单词。

s='''When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the Powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.'''
s=s.lower().replace(',','').replace('.','')
lst=s.split(' ')
dic={
   }
for word in lst:
    dic[word]=dic.get(word,0)+1
print(dic)
newlst=[(v,k) for k,v in dic.items()]
newlst.sort()
print(newlst[-1:-6:-1])

在这里插入图片描述
13.编写程序,使用嵌套字典描述表中内容之间的映射关系,输出字典中每种颜色的事物数目,如紫色的食物有三个。
在这里插入图片描述

dic_menu={
   "蔬菜":{
   "青菜":"绿色","胡萝卜":"橙色","茄子":"紫色","毛豆":"绿色"},
          "水果":{
   "山竹":"紫色","香蕉":"黄色","橙子":"橙色","草莓":"红色"},
          "饮料":{
   "椰子汁":"白色","西瓜汁":"红色","玉米汁"
  • 125
    点赞
  • 373
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zxm1123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值