栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python:按顺序输出成绩倒数第二的学生姓名

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python:按顺序输出成绩倒数第二的学生姓名

HackerRank题解:

#python3.0上

要求输入先输入一个整数n,表示学生的数目,再输入一组[["herry",50],["pote",45],["hello",45]]这样的数,然后输出:

hello

pote

初代码:

arrag = dict() #定义字典用来存值
temp =list() #存成绩
temp1 = list()#存姓名
for x in range(int(input())):
        name = input()
        score=float(input())
        arrag[name]=score
for value in arrag.values():
    temp.append(value)
temp.sort()
a=min(temp)
while a==min(temp):
        temp.remove(min(temp))
temp.remove(min(temp))
for key in arrag.keys():
    if arrag[key] ==min(temp):
        temp1.append(key)
print(temp)
print(sorted(temp1))

局部优化后的代码:

arrag = dict()  #定义字典用来存值
for x in range(int(input())):
        name = input()
        score=float(input())
        arrag[name]=score
temp=arrag.values()
data=sorted(list(set(temp)))[1]
lowest = [] #存姓名
for key in arrag.keys():
    if arrag[key]==data:
        lowest.append(key)
for name in sorted(lowest):
    print(name)

优化部分:主要是用函数优化减少了部分循环,其中set()的利用最为典型,用来创建一个无序不重复集合,不用再去一个个的删除重复部分,可以直接的排序成绩,取得倒数第二的成绩。

浓缩版(copy大佬):

marksheet = []
for _ in range(0,int(input())):
    marksheet.append([input(), float(input())])

second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
print('n'.join([a for a,b in sorted(marksheet) if b == second_highest]))

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/302354.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号