题目:
列表 ls 中存储了我国 39 所 985 高校所对应的学校类型,请以这个列表为数据变量,完善 Python 代码,统计输出各类型的数量。
ls=["综合","理工","综合","综合","综合","综合","综合","综合","综合","综合",\"师范","理工","综合","理工","综合","综合","综合","综合","综合","理工",\"理工","理工","理工","师范","综合","农林","理工","综合","理工","理工",\"理工","综合","理工","综合","综合","理工","农林","民族","军事"]
解答:
ls = ["综合", "理工", "综合", "综合", "综合", "综合", "综合", "综合", "综合", "综合",\
"师范", "理工", "综合", "理工", "综合", "综合", "综合", "综合", "综合","理工",\
"理工", "理工", "理工", "师范", "综合", "农林", "理工", "综合", "理工", "理工", \
"理工", "综合", "理工", "综合", "综合", "理工", "农林", "民族", "军事"]
d = {} #创建空字典 用计算机术语来说叫初始化
for word in ls:
d[word] = d.get(word,0)+1
for k,v in d.items():
print(k,":",v)# dict的items方法可以取出key与value。
/参考答案的方案
/print("{}:{}".format(k, d[k]))
/参考答案用format配合d[key]取value。注:迭代dict取出的是key!!!
输出答案:
综合 : 20
理工 : 13
师范 : 2
农林 : 2
民族 : 1
军事 : 1
网友评论