试题2

作者: 空白人间 | 来源:发表于2018-09-09 18:15 被阅读2次

    题目:

    列表 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
    

    相关文章

      网友评论

        本文标题:试题2

        本文链接:https://www.haomeiwen.com/subject/ijsdgftx.html