如何按group分组生成与输入位置最短距离的Python字典
核心问题
你当前的代码只单独存储了距离值,没有将距离和对应的点位code、group字段做绑定,所以无法直接关联生成目标格式的结果。
修改思路
- 遍历全量点位判断是否在半径范围内时,直接同步计算距离,同时绑定该点位的
code、group、距离三个字段,避免后续关联错乱 - 对每个输入圆心的符合条件的点位,按
group分组,每组内取距离最小的点位即可
修改后完整代码
def search(inputFile, LocationCode, radius): from math import sqrt data = dict() with open(inputFile) as file: next(file) for line in file.readlines(): line = line.strip('\n').replace(' ', '') # 处理字段间的空格,避免分割异常 code, x, y, group, n, importance = line.split(",") # 提前转换坐标为float,避免后续重复转换 data[code] = (float(x), float(y), group, n, importance) float_rad = float(radius) final_result = [] # 存储最终返回结果 for loc_code in LocationCode: # 获取当前搜索圆心的坐标 center_x, center_y = data[loc_code][0], data[loc_code][1] # 存储当前圆心下所有符合条件的点位:格式为(code, group, 距离) valid_points = [] for code, val in data.items(): x, y, group, _, _ = val # 跳过自身点位 if code == loc_code: continue dist_square = (x - center_x)**2 + (y - center_y)**2 if dist_square < float_rad**2: dist = sqrt(dist_square) valid_points.append((code, group, dist)) # 按group分组,每组保留距离最小的点位 group_min_dict = {} for point in valid_points: code, group, dist = point if group not in group_min_dict or dist < group_min_dict[group][1]: group_min_dict[group] = (code, dist) final_result.append(group_min_dict) return final_result # 测试运行 output = search('sample.csv', ["x26", "x52"], 3.5) print(output)
代码说明
- 去掉了原代码中冗余的三角函数导入,你提供的是平面x/y坐标,不需要经纬度距离计算相关的函数
- 所有关联字段全程绑定存储,不会出现距离和点位对应不上的问题
- 输出结果完全符合你要求的格式,每个输入点位对应一个按group分组的字典,值为最短点位的(code, 距离)元组
内容的提问来源于stack exchange,提问作者Peanut Jams
相关产品推荐
相关产品推荐

