我如何根据下面给出的数据列表使用while循环返回3个最大值:
list_of_numbers = [
['A',12.0],
['B',52.0],
['C',5.5],
['D',77.0],
['E',55.0],
['F',3.7,]
]
所需的输出:
[
['D',77.0],
['E',55.0],
['B',52.0]
]
答案 0 :(得分:1)
In [9]: list_of_numbers = [
...: ['A', 12.0],
...: ['B', 52.0],
...: ['C', 5.5],
...: ['D', 77.0],
...: ['E', 55.0],
...: ['F', 3.7]
...: ]
In [10]: sorted(list_of_numbers, key=lambda x: x[1], reverse=True)[:3]
Out[10]: [['D', 77.0], ['E', 55.0], ['B', 52.0]]
key=lambda x: x[1]
意味着按照所有这些列表的第二个元素对其进行排序
reverse=True
按降序排列
[:3]
是一个切片,它从已排序的列表中获取元素0、1和2,因此前三名