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

如何对numpy的distances数组升序排序并同步对应indices数组

同步排序numpy数组distances和indices的方法

要实现distances升序排序的同时让indices同步对应,核心是利用numpy的argsort()函数获取排序的索引映射,再用该索引对两个数组重新取值。

具体步骤

  1. 获取排序索引:使用np.argsort(distances)得到distances升序排列后,每个元素在原数组中的索引位置。
  2. 同步排序两个数组:用得到的索引分别对distances和indices进行索引,即可得到对应排序后的数组。

示例代码

import numpy as np

# 模拟输入数组
distances = np.array([5.2, 1.3, 3.7, 0.8])
indices = np.array([3, 1, 4, 2])

# 获取distances升序排序的索引
sort_order = np.argsort(distances)

# 同步排序两个数组
sorted_distances = distances[sort_order]
sorted_indices = indices[sort_order]

# 输出结果
print("排序后的distances:", sorted_distances)
print("同步排序后的indices:", sorted_indices)

输出结果

排序后的distances: [0.8 1.3 3.7 5.2]
同步排序后的indices: [2 1 4 3]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:33:05