我写了这段代码来寻找最大的值,这段代码运行得很好,但是我想把它切成前五个值,并且只显示前五个。代码运行得很好,但我想把它切成前5个值,只显示前5个值,我该怎么切?请帮助我!!!!!!!!!!。先谢谢你
Student=[a, b, c, d, e, f, g, h, I, j, k, l, m, n, O, p, q, r, s, t, u, v, w, x, y, z]
marks=[45, 78,12,14,48,43,47,98,35,80]
student_marks= dict(zip(student, marks))
for i in student_marks:
max_key= max( student_marks, key= student_marks.get)
student_marks.pop(max_key)
all_values= student_marks.values()
max_values= max(all_values)
print(max_key, max_values)
你可以试试这段代码,将列表按递减顺序排序,然后只打印列表中的前5个元素。
max_values=[45, 78, 12, 14, 48, 43, 47, 98, 35, 80]
max_values.sort(reverse=True) # Sort the list by deacreasing order
print(max_values[:5]) # Print only the 5 first values of the list
EDIT:我采取的假设,你有一个列表的学生姓名和分数.首先,使用 list.sort
函数来按照你需要的方式对数据进行排序,其次,使用 print(list_of_marks[:5])
只取前5个值。
list_of_marks = [['a', 45], ['b', 78], ['c', 12], ['d', 14], ['e', 48],
['f', 43], ['g', 47], ['h', 98], ['I', 35], ['j', 80]]
list_of_marks.sort(reverse=True, key=lambda x: x[1])
print(list_of_marks[:5])
输出:
[['h', 98], ['j', 80], ['b', 78], ['e', 48], ['g', 47]]