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

如何在Python中按X列升序排序并保持X-Y配对关系?

Python中按X值排序并保持(X,Y)配对的实现方法

你可以通过以下两种常见方式实现需求,核心思路都是先维持(X,Y)的配对关系,再按X值排序,最后拆分回原矩阵结构:

方法一:利用zip配对后排序再拆分

这种方法直观易懂,先把对应的X和Y值配对成元组,排序后再拆分回列表:

matrix = [[10, -9, 8], [1, 15, 5]]
# 将X和Y一一配对成元组列表
paired_items = list(zip(matrix[0], matrix[1]))
# 按元组的第一个元素(X值)升序排序
sorted_paired = sorted(paired_items, key=lambda item: item[0])
# 拆分排序后的元组,重新组成矩阵
sorted_matrix = [list(col) for col in zip(*sorted_paired)]
print(sorted_matrix)  # 输出:[[-9, 8, 10], [15, 5, 1]]

方法二:通过索引排序重排元素

先获取X值排序后的索引顺序,再用该索引重新提取X和Y的元素:

matrix = [[10, -9, 8], [1, 15, 5]]
# 获取按X值升序排列的索引列表
sorted_indices = sorted(range(len(matrix[0])), key=lambda idx: matrix[0][idx])
# 根据排序后的索引重新生成X、Y列表
sorted_x = [matrix[0][i] for i in sorted_indices]
sorted_y = [matrix[1][i] for i in sorted_indices]
sorted_matrix = [sorted_x, sorted_y]
print(sorted_matrix)  # 输出:[[-9, 8, 10], [15, 5, 1]]

内容的提问来源于stack exchange,提问作者Projetos Programação

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 04:35:01