如何按列对多维数组进行排序? [英] How to sort multidimensional array by column?
问题描述
有没有办法使用 sort() 方法或任何其他方法按列对列表进行排序?假设我有列表:
<预><代码>[[约翰,2],[吉姆,9],[杰森,1]]我想对它进行排序,使其看起来像这样:
<预><代码>[[杰森,1],[约翰,2],[吉姆,9],]这样做的最佳方法是什么?
现在我遇到了索引超出范围的错误.我有一个二维数组,可以说 1000 行 b 3 列.我想根据第三列对其进行排序.这是正确的代码吗?
sorted_list = sorted(list_not_sorted, key=lambda x:x[2])
是的.sorted
内置函数接受一个 key
参数:
sorted(li,key=lambda x: x[1])出 [31]: [['杰森', 1], ['约翰', 2], ['吉姆', 9]]
注意 sorted
返回一个新列表.如果您想就地排序,请使用列表的 .sort
方法(该方法也方便地接受 key
参数).
或者,
from 操作符导入 itemgetter排序(li,key = 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]]
这篇关于如何按列对多维数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!