You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用lambda函数对二维数组按指定索引排序?

不用Lambda实现二维数组按指定索引排序的最优方案

核心方案:使用operator.itemgetter

Python的operator模块提供的itemgetter是替代lambda做排序key的最优选择——它是C语言实现的,性能比lambda更优,尤其是处理大规模数据时。

代码示例

1. 按索引0排序(你的需求场景)

import operator

array = [[2,1],[1,4],[3,5]]
array.sort(key=operator.itemgetter(0))
print(array)  # 输出: [[1,4],[2,1],[3,5]]

2. 按任意索引排序(比如索引1)

import operator

array = [[2,1],[1,4],[3,5]]
array.sort(key=operator.itemgetter(1))
print(array)  # 输出: [[2,1],[1,4],[3,5]]

为什么itemgetter是最优?

  • 性能更高:itemgetter直接调用底层C代码,避免了lambda表达式在Python层面的函数调用开销,数据量越大,优势越明显。
  • 代码更简洁:尤其是需要按多个索引排序时(比如itemgetter(0,1)),写法比嵌套lambda更直观。

备选:自定义函数

如果不想导入模块,也可以用自定义函数,但性能不如itemgetter:

def get_index(n):
    def inner(arr):
        return arr[n]
    return inner

array = [[2,1],[1,4],[3,5]]
array.sort(key=get_index(0))
print(array)  # 输出: [[1,4],[2,1],[3,5]]

这种方式通过闭包实现动态指定索引,但因为是Python函数调用,速度比itemgetter慢。

内容的提问来源于stack exchange,提问作者Jacob G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:50:36