排序二维列表python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18563680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:06:41  来源:igfitidea点击:

Sorting 2D list python

pythonlistsorting

提问by Chinthaka Nadun Ratnaweera

I have following type of list

我有以下类型的列表

lst = [
    [1, 0.23],
    [2, 0.39],
    [4, 0.31],
    [5, 0.27],
]

I want to sort this in descending order of the second column. I tried 'sorted' function in python. But gives me a 'TypeError' : 'float' object is unsubscriptable. Please help me solve this problem.

我想按第二列的降序对其进行排序。我在 python 中尝试了“排序”功能。但是给了我一个 'TypeError' :'float' 对象是不可订阅的。请帮我解决这个问题。

回答by Martijn Pieters

To sort a list of lists on the second column, use operator.itemgetter()for ease and clarity:

要对第二列上的列表进行排序,operator.itemgetter()为方便和清晰起见,请使用:

from operator import itemgetter
outputlist = sorted(inputlist, key=itemgetter(1), reverse=True)

or, to sort in-place:

或者,就地排序:

from operator import itemgetter
inputlist.sort(key=itemgetter(1), reverse=True)

itemgetter()is a little faster than using a lambdafor the task.

itemgetter()lambda对任务使用 a 快一点。

Demo:

演示:

>>> from operator import itemgetter
>>> inputlist = [
...     [1, 0.23],
...     [2, 0.39],
...     [4, 0.31],
...     [5, 0.27],
... ]
>>> sorted(inputlist, key=itemgetter(1), reverse=True)
[[2, 0.39], [4, 0.31], [5, 0.27], [1, 0.23]]

You'd only see your exception if you had floating point values in your inputlist directly:

如果您的输入列表中直接有浮点值,您只会看到您的异常:

>>> inputlist.append(4.2)
>>> inputlist
[[1, 0.23], [2, 0.39], [4, 0.31], [5, 0.27], 4.2]
>>> sorted(inputlist, key=itemgetter(1), reverse=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object is not subscriptable

(for Python 3; Python 2's error message is slightly different, resulting in TypeError: 'float' object has no attribute '__getitem__'instead).

(对于 Python 3;Python 2 的错误消息略有不同,结果TypeError: 'float' object has no attribute '__getitem__'改为)。

This is because the itergetter(1)call is applied to all elements in the outer list but only works on nested ordered sequences, not on the one floating point value now added.

这是因为该itergetter(1)调用适用于外部列表中的所有元素,但仅适用于嵌套的有序序列,而不适用于现在添加的一个浮点值。

回答by dawg

You can use a lambda:

您可以使用 lambda:

>>> li=[[1, 0.23],
... [2, 0.39],
... [4, 0.31],
... [5, 0.27]]
>>> sorted(li,key=lambda l:l[1], reverse=True)
[[2, 0.39], [4, 0.31], [5, 0.27], [1, 0.23]]

Or the other way:

或者换一种方式:

>>> sorted(li,key=lambda l:l[1])
[[1, 0.23], [5, 0.27], [4, 0.31], [2, 0.39]]