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

如何按子数组长度对NumPy数组的子数组排序且不改变其内部内容

NumPy数组按子数组长度排序实现方案

方法1:Python原生排序(通用简便方案)

不管你当前用的是Python原生嵌套列表,还是NumPy的object类型数组,都可以直接用内置的sorted函数实现,不会修改子数组内部内容:

# 示例输入(原生列表)
myArray = [[1,2,3,4,5,6,7],
           [8,9,10,11],
           [12],
           [13],
           [14,15,16,17,18,19,20,21,22,23,24]]

# 按子数组长度降序排序
sorted_array = sorted(myArray, key=lambda x: len(x), reverse=True)

如果输入是NumPy数组,排序后转回来即可:

import numpy as np

# 示例输入(NumPy object类型数组)
myArray = np.array([[1,2,3,4,5,6,7],
                    [8,9,10,11],
                    [12],
                    [13],
                    [14,15,16,17,18,19,20,21,22,23,24]], dtype=object)

sorted_array = np.array(sorted(myArray, key=lambda x: len(x), reverse=True), dtype=object)

方法2:纯NumPy实现(无需转换类型)

如果你不想做列表和NumPy数组的类型转换,可以直接通过长度计算+索引重排实现:

import numpy as np

myArray = np.array([[1,2,3,4,5,6,7],
                    [8,9,10,11],
                    [12],
                    [13],
                    [14,15,16,17,18,19,20,21,22,23,24]], dtype=object)

# 计算每个子数组的长度
length_arr = np.vectorize(len)(myArray)
# 按长度降序获取排序索引
sort_idx = np.argsort(-length_arr)
# 按索引重排原数组
sorted_array = myArray[sort_idx]

两种方法输出都和你给出的期望结果完全一致,子数组内部内容不会有任何改动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:36:05