实现的代码如下:
stu = {"name": "", "english": 0, "python": 0, "math": 0}
# 输入学生姓名和成绩
name, english, python, math = input().split()
stu["name"] = name
stu["english"] = int(english)
stu["python"] = int(python)
stu["math"] = int(math)
# 计算平均成绩并添加到字典中
avg = (stu["english"] + stu["python"] + stu["math"]) / 3
stu["avg"] = avg
# 由高到低排序各科成绩
sorted_scores = sorted(stu.items(), key=lambda x: x[1] if isinstance(x[1], int) else -1, reverse=True)
# 输出学生姓名和成绩
print(stu["name"], end="")
for item in sorted_scores:
if item[0] != "name":
print("{:7.2f}".format(item[1]), end="")
print("{:7.2f}".format(avg))
说明:
sorted_scores = sorted(stu.items(), key=lambda x: x[1] if isinstance(x[1], int) else -1, reverse=True)
这段代码的作用是将字典 stu
按照值进行排序,排序的方式是将值转换为整数后进行排序,如果值无法转换为整数,则将其排在最后。排序结果按照降序排列。最终返回的是一个列表,其中每个元素是一个元组,元组的第一个元素是字典中的键,第二个元素是对应的值。
print("{:7.2f}".format(avg))
保留两位小数,并且总共占据7个字符的宽度,不足的部分用空格填充。可以去修改{:7.2f}中的数字7,表示空格宽度。
另外,推荐读者两个比较好的壁纸网址:极简壁纸
、Desktop wallpapers,
如果需要保证整数也能保留两位小数,可以在使用 round() 函数时先将数值转化为浮点数,然后再保留两位小数,例如:
score = 95 score = round(float(score), 2)
这样输出的 score 就会是 95.00,即整数也被保留了两位小数。
如果需要对多个成绩进行排序,可以使用内置的 sorted() 函数,将成绩列表作为参数传入,例如:
scores = [95.55, 90.00, 78.67, 86.23] sorted_scores = sorted(scores)
这样得到的 sorted_scores 就是成绩从小到大排列的列表了,例如: [78.67, 86.23, 90.0, 95.55]。如果需要从大到小排列,可以传入参数 reverse=True,例如:
sorted_scores = sorted(scores, reverse=True)
得到的 sorted_scores 就是成绩从大到小排列的列表了,例如: [95.55, 90.0, 86.23, 78.67]。