基于子数组第二个元素的Python排序多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20099669/
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-18 19:31:03  来源:igfitidea点击:

Python Sort Multidimensional Array Based on 2nd Element of Subarray

pythonarrayslistsortingmultidimensional-array

提问by Federico Capello

I have an array like this:

我有一个这样的数组:

[['G', 10], ['A', 22], ['S', 1], ['P', 14], ['V', 13], ['T', 7], ['C', 0], ['I', 219]]

I'd like to sort it based on the 2nd element in descending order. An ideal output would be:

我想根据降序的第二个元素对其进行排序。理想的输出是:

[['I', 219], ['A', 22], ['P', 14], ... ]

采纳答案by falsetru

list.sort, sortedaccept optional keyparameter. keyfunction is used to generate comparison key.

list.sort,sorted接受可选key参数。key函数用于生成比较键。

>>> sorted(lst, key=lambda x: x[1], reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]

>>> sorted(lst, key=lambda x: -x[1])
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]

>>> import operator
>>> sorted(lst, key=operator.itemgetter(1), reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]

回答by Nikhil Kollanoor

Use itemgetter

itemgetter

from operator import itemgetter
a = [[1, 3, 5], [2, 511, 7], [17, 233, 1]]
a = sorted(a, key=itemgetter(1))

Output : [[1, 3, 5], [17, 233, 1], [2, 511, 7]]

输出:[[1, 3, 5], [17, 233, 1], [2, 511, 7]]

itemgettercan also be used to sort by multiple subarrays.

itemgetter也可用于按多个子数组排序。

回答by Manik

x= [[8, 9, 7],
    [1, 2, 3],
    [5, 4, 3],
    [4, 5, 6]]
x.sort(cmp=lambda x,y: cmp(x[0],y[0]))
print x

回答by Nidhi Alipuria

Do this:

做这个:

Sort the multi-dimensional array in descending order on the basis of 2nd column:

在第 2 列的基础上按降序对多维数组进行排序:

list_name.sort(key=lambda x:x[1],reverse=True)