在Python中,可以使用zip函数和sorted函数来按另一个向量对向量进行排序。下面是一个示例代码:
# 定义两个向量
vector1 = [4, 2, 7, 1, 5]
vector2 = [9, 6, 3, 8, 10]
# 使用zip函数将两个向量合并成一个元组列表,每个元组包含一个元素来自vector1和vector2
combined = zip(vector1, vector2)
# 使用sorted函数对combined进行排序,按照vector2的值进行排序
sorted_combined = sorted(combined, key=lambda x: x[1])
# 拆分排序后的combined,得到排序后的vector1和vector2
sorted_vector1 = [x[0] for x in sorted_combined]
sorted_vector2 = [x[1] for x in sorted_combined]
# 打印排序后的结果
print(sorted_vector1) # 输出:[7, 2, 4, 5, 1]
print(sorted_vector2) # 输出:[3, 6, 9, 10, 8]
在上面的代码中,首先使用zip函数将vector1和vector2合并成一个元组列表combined。然后使用sorted函数对combined进行排序,通过key参数指定按照vector2的值进行排序。最后使用列表推导式将排序后的combined拆分成排序后的vector1和vector2。