如何基于原点距离对两个并行数组排序并输出有序对?
解决方案
首先,处理并行数组排序的最优方式是把对应的x、y坐标打包成坐标对列表,这样排序逻辑会更清晰。以下是修改后的完整代码:
import math n = int(input("How many coordinates would you like to enter:")) coordinates = [] # 直接输入坐标并存为列表的元组,替代两个独立数组 for _ in range(n): x = int(input("Enter X:")) y = int(input("Enter Y:")) coordinates.append( (x, y) ) # 按到原点的距离排序 # math.hypot(x, y) 等价于 math.sqrt(x**2 + y**2),写法更简洁 coordinates.sort(key=lambda point: math.hypot(point[0], point[1])) # 输出排序后的有序对 print("Sorted coordinates by distance to origin:") for x, y in coordinates: print(f"({x}, {y})")
关键说明:
- 用
list.append( (x,y) )直接存储坐标对,避免维护两个独立数组的麻烦,这是Python里处理这类关联数据更常规的方式。 sort()方法的key参数指定排序依据:lambda point: math.hypot(point[0], point[1])会计算每个坐标到原点的距离,以此作为排序的关键字。- 如果一定要保留原来的两个数组结构,排序后可以再拆分回去:
# 拆分回两个数组(如果需要) myArray1_sorted = [p[0] for p in coordinates] myArray2_sorted = [p[1] for p in coordinates]
内容的提问来源于stack exchange,提问作者Antwon
相关产品推荐
相关产品推荐

