python - 基于子数组的第二个元素对多维数组进行排序

标签 python arrays list sorting multidimensional-array

我有一个这样的数组:

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

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

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

最佳答案

list.sortsorted接受可选的 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], ...]

关于python - 基于子数组的第二个元素对多维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20099669/

相关文章:

python - 测试 Django 命令文件或标准输入

php - 我如何使用 php 在多维数组中按键分组项目

c++ - C++-std::list.erase()不删除元素

python - 创建 Python 子模块

python - 我正在寻找一个高效的 django 查询集来阻止这么多人访问我的数据库

python - NotADirectoryError : [WinError 267] The directory name is invalid error while invoking Firefox through Selenium Python

java - 对象数组还是带数组的对象?

python - python 中的 4 维零数组

python - 从 For 循环 Python 中的迭代总数中减去字典值

python - 列表/序列的正则表达式模拟