如何获取与数组A匹配的数组B对应点的索引列表?
获取匹配点的索引实现思路
先看原有的Python代码及功能:
A = [(1,2,3),(2,3,4)] B = [(2,4,3),(1,8,1),(2,3,5),(1,5,3)] def closestNew(A,B): C = {} for bp in B: closestDist = -1 for ap in A: dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2)) if(closestDist > dist or closestDist == -1): C[bp] = ap closestDist = dist return C
这个函数会返回B中每个点对应的A里最近点的映射,实际输出结果为:
{(2, 4, 3): (1, 2, 3), (1, 8, 1): (1, 2, 3), (2, 3, 5): (2, 3, 4), (1, 5, 3): (1, 2, 3)}
(注:你提供的输出写反了键值对,原函数是以B点为键、A点为值的映射,后续思路基于正确逻辑调整)
现在需要获取A中每个点对应的B点在原B列表中的索引,期望结果是idx=[0,2],以下是两种实用实现思路:
方法一:修改原函数,直接记录索引
遍历B的时候用enumerate同时拿到元素和它的索引,在确定每个B点对应的最近A点后,把A点作为键存储对应的B点索引,最后按A的顺序提取索引即可,逻辑和原函数完全一致,还能直接拿到需要的结果:
A = [(1,2,3),(2,3,4)] B = [(2,4,3),(1,8,1),(2,3,5),(1,5,3)] def closestNewWithIndices(A, B): # 存储A点到B点的映射(和原函数输出的反向映射一致) point_map = {} # 存储A点到对应B点索引的映射 index_map = {} for idx, bp in enumerate(B): closest_dist = -1 target_ap = None for ap in A: # 计算欧氏距离的平方(比开根号更快,不影响比较结果) dist = sum(((bp[i] - ap[i])**2 for i in range(3))) if closest_dist == -1 or dist < closest_dist: closest_dist = dist target_ap = ap # 按原函数逻辑:如果多个B点对应同一个A点,后面的会覆盖前面的 point_map[target_ap] = bp index_map[target_ap] = idx # 按A的顺序提取索引,得到期望的列表 idx_list = [index_map[ap] for ap in A] return point_map, idx_list # 调用示例 result_map, idx = closestNewWithIndices(A, B) print("点映射结果:", result_map) # {(1, 2, 3): (2, 4, 3), (2, 3, 4): (2, 3, 5)} print("对应索引:", idx) # [0, 2]
方法二:基于原函数输出反向查找索引
如果不想改动原函数,可以先拿到原函数的输出,再反向构建A点到B点的映射,最后用B.index()获取每个B点的索引:
# 原函数保持不变 def closestNew(A,B): C = {} for bp in B: closestDist = -1 for ap in A: dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2)) if(closestDist > dist or closestDist == -1): C[bp] = ap closestDist = dist return C # 步骤1:获取原函数的映射结果 original_map = closestNew(A, B) # 步骤2:反向构建A点到B点的映射 reverse_map = {ap: bp for bp, ap in original_map.items()} # 步骤3:按A的顺序查找每个B点在原列表中的索引 idx = [B.index(reverse_map[ap]) for ap in A] print(idx) # [0, 2]
⚠️ 注意:这种方法有局限性,如果B列表中存在重复的点,B.index()只会返回该点第一次出现的索引,结果可能不符合预期,因此优先推荐方法一。
内容的提问来源于stack exchange,提问作者TullMesh
相关产品推荐
相关产品推荐

