方法排序列表?

时间:2021-02-18 14:05:22

I have a list of lists (can't be tuples since I have to generate it dynamically) and it is structured as a list of lists of one int and one float Like so:

我有一个列表列表列表(不能是元组,因为我必须动态生成它),它的结构是由一个int和一个float的列表组成的列表,如下所示:

[[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]

I want to get it sorted but I have only managed to get the built in sorting function to sort it by the first element of the lists or not do anything, but I need to sort them by the second element of the list and I don't want to implement my own sorting function. So an example of what I would want is:

我想把它分类,但我只有设法让建成的排序函数,它的第一个元素列表或不做任何事,但我需要第二个元素排序的列表,我不想实现自己的排序功能。我想要的一个例子是

[[1,1.0345],[3,4.89],[2,5.098],[2,5.97]]

Could someone tell me how to get one of the built in sorting functions to do this?

有人能告诉我如何让一个内置的排序函数来做这个吗?

3 个解决方案

#1


18  

Pass the key argument.

通过参数的关键。

L.sort(key=operator.itemgetter(1))

#2


11  

>>> l = [[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
>>> l.sort(key=lambda x: x[1])
>>> l
[[1, 1.0345], [3, 4.8899999999999997], [2, 5.0979999999999999], [2, 5.9699999999999998]]

#3


3  

How about using they key parameter of sorted...

使用它们排序的关键参数……

sorted_list = sorted([[1,1.0345],[3,4.89],[2,5.098],[2,5.97]], key=lambda x: x[1])

This tells python to sort the list of lists using the item at index 1 of each list as the key for the compare.

这告诉python在每个列表的索引1中使用条目排序列表,作为比较的键。

#1


18  

Pass the key argument.

通过参数的关键。

L.sort(key=operator.itemgetter(1))

#2


11  

>>> l = [[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
>>> l.sort(key=lambda x: x[1])
>>> l
[[1, 1.0345], [3, 4.8899999999999997], [2, 5.0979999999999999], [2, 5.9699999999999998]]

#3


3  

How about using they key parameter of sorted...

使用它们排序的关键参数……

sorted_list = sorted([[1,1.0345],[3,4.89],[2,5.098],[2,5.97]], key=lambda x: x[1])

This tells python to sort the list of lists using the item at index 1 of each list as the key for the compare.

这告诉python在每个列表的索引1中使用条目排序列表,作为比较的键。