问题描述
有没有使用sort()方法或任何其他方法来排序列列表的方式吗?可以说我有名单:
[
[约翰,2]
[吉姆,9]
[杰森,1]
]
和我想对它进行排序,使它看起来像这样:
[
[杰森,1]
[约翰,2]
[吉姆,9]
]
什么是做到这一点的最佳方法?
编辑:
现在我遇到了一个索引超出范围的错误。我有一个二维数组,它是可以说1000行B 3列。我想基于第三列排序。这是正确的code是什么?
sorted_list =排序(list_not_sorted,键=拉姆达X:X [2])
是的。在整理
内置接受键
参数:
排序(李键=拉姆达X:X [1])
出[31]:[['贾森',1],['约翰',2],['吉姆',9]
注意,整理
返回一个新的列表。如果你想就地进行排序,使用的.sort
列表的方法(也方便,接受键
参数)。
或可替换地,
从运营商进口itemgetter
排序(李键= itemgetter(1))
出[33]:[['贾森',1],['约翰',2],['吉姆',9]
。
Is there a way to use the sort() method or any other method to sort a list by column? Lets say I have the list:
[
[John,2],
[Jim,9],
[Jason,1]
]
And I wanted to sort it so that it would look like this:
[
[Jason,1],
[John,2],
[Jim,9],
]
What would be the best approach to do this?
Edit:
Right now I am running into an index out of range error. I have a 2 dimensional array that is lets say 1000 rows b 3 columns. I want to sort it based on the third column. Is this the right code for that?
sorted_list = sorted(list_not_sorted, key=lambda x:x[2])
Yes. The sorted
built-in accepts a key
argument:
sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]
note that sorted
returns a new list. If you want to sort in-place, use the .sort
method of your list (which also, conveniently, accepts a key
argument).
or alternatively,
from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]
这篇关于如何排序列多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!