赞
踩
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={
"蔬菜":{
"青菜":"绿色","胡萝卜":"橙色","茄子":"紫色","毛豆":"绿色"},
"水果":{
"山竹":"紫色","香蕉":"黄色","橙子":"橙色","草莓":"红色"},
"饮料":{
"椰子汁":"白色","西瓜汁":"红色","玉米汁":</
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。