根据子数组的第二个元素对多维数组进行排序 [英] Sort multidimensional array based on 2nd element of the subarray
本文介绍了根据子数组的第二个元素对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数组:
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], ... ]
推荐答案
list.sort
, sorted
accept optional key
parameter. key
function is used to generate comparison 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], ...]
这篇关于根据子数组的第二个元素对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文