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

如何高效查找不同长度数组组成的列表中最小值的索引?

高效查找多长度numpy数组列表中最小值的索引

给定由不同长度numpy数组组成的列表,我们需要快速定位其中最小值的位置,并按(元素在子数组的索引, 子数组在列表的索引)格式输出(示例中最小值-11的原索引为(2, 0),对应输出(0, 2))。以下是两种高效实现方案:

方案一:基于numpy向量化合并(适合内存充足场景)

利用numpy的底层优化操作,通过合并数组快速定位全局最小值:

import numpy as np

L = [
    np.array([-10, -8, -3, 2, 1, 5, 12]),
    np.array([-9, -4, -1, 3, 5]),
    np.array([-11, -5, -4, 0, 1, 5, 7, 13, 18, 22])
]

# 计算各子数组长度及累积长度
lengths = np.array([len(arr) for arr in L])
cumulative_lengths = np.concatenate(([0], np.cumsum(lengths)))

# 合并数组并找到全局最小值的索引
flat_array = np.concatenate(L)
global_min_pos = flat_array.argmin()

# 定位对应的子数组和元素索引
sub_array_idx = np.searchsorted(cumulative_lengths, global_min_pos, side='right') - 1
element_idx = global_min_pos - cumulative_lengths[sub_array_idx]

# 按要求格式输出
result = (element_idx, sub_array_idx)
print(result)  # 输出:(0, 2)

优势:完全依赖numpy的C级优化操作,无Python循环,处理大数据量时效率极高。

方案二:逐数组遍历比较(适合内存受限场景)

当单个数组体积过大、合并会占用过多内存时,可逐个遍历数组记录最小值:

import numpy as np

L = [
    np.array([-10, -8, -3, 2, 1, 5, 12]),
    np.array([-9, -4, -1, 3, 5]),
    np.array([-11, -5, -4, 0, 1, 5, 7, 13, 18, 22])
]

min_value = float('inf')
result_index = (0, 0)

for sub_idx, arr in enumerate(L):
    current_min_idx = arr.argmin()
    current_min_val = arr[current_min_idx]
    if current_min_val < min_value:
        min_value = current_min_val
        result_index = (current_min_idx, sub_idx)

print(result_index)  # 输出:(0, 2)

优势:无需合并数组,内存占用更低,适合数组规模极大的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:05:21