以与第一个列表相同的方式对第二个列表进行排序

sorting 2nd list in the same way 1nd list sorted

假设我必须列出 X, Y 个大小为 N 的整数。向量 Y, 对应于 X ,(xi标签为yi)

现在我想对 X 进行排序,然后按相同的顺序对 Y 进行排序 如果我在 java 中完成,我会覆盖排序方法,但我在 python 中有点新... 有什么好的方法吗?

不确定这是否是您所说的“不错”:

combo = sorted(zip(x,y))

sorted_x = [a for a,b in combo]
sorted_y = [b for a,b in combo]

使用 zip()X 中的每个数据点与其在 Y 中的关联数据点绑定。然后使用 sorted() 和列表理解来读取结果:

x = [3, 1, 2]
y = [5, 4, 6]

# Prints [4, 6, 5]
# These values are sorted in ascending order of corresponding x-value:
# 1 --> 4
# 2 --> 6
# 3 --> 5
result = [y_data for _, y_data in sorted(zip(x, y))]

print(result)