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

如何将y数组元素与排序后的新数组c重新关联匹配?

实现方法

核心思路是保留原数组x与y的对应关系,在对x排序的同时同步关联对应的y值,完全避免硬编码。以下是两种常用编程语言的具体实现:

Matlab 实现

利用sort函数的第二个返回值获取排序后元素在原数组中的索引,再通过索引提取对应y值:

x = [11; 22; 5; 12; 42; 21; 41; 32; 10];
y = [0; 1; 0; 1; 0; 1; 0; 1; 0];

% 对x升序排序,同时获取原元素的索引位置
[c, sort_indices] = sort(x);
% 根据索引提取与c匹配的y数组
matched_y = y(sort_indices);

运行后matched_y即为与c一一对应的y数组,结果为[0; 0; 0; 1; 1; 1; 1; 0; 0]。

Python 实现

方法1:纯Python(无第三方依赖)

将x与y配对成元组,按x的值排序后拆分即可:

x = [11, 22, 5, 12, 42, 21, 41, 32, 10]
y = [0, 1, 0, 1, 0, 1, 0, 1, 0]

# 把x和y配对,按x的值升序排序
sorted_pairs = sorted(zip(x, y), key=lambda item: item[0])
# 拆分排序后的元组,得到c和对应的y数组
c = [item[0] for item in sorted_pairs]
matched_y = [item[1] for item in sorted_pairs]

方法2:NumPy 实现

利用argsort获取排序索引,再通过索引提取对应值:

import numpy as np

x = np.array([11, 22, 5, 12, 42, 21, 41, 32, 10]).reshape(-1, 1)
y = np.array([0, 1, 0, 1, 0, 1, 0, 1, 0]).reshape(-1, 1)

# 获取x升序排序的索引位置
sort_indices = np.argsort(x, axis=0)
# 生成排序后的c和匹配的y数组
c = x[sort_indices].flatten()
matched_y = y[sort_indices].flatten()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:40:26