如何基于区间描述匹配连接两个区间列表?
井区间结束值匹配问题
给定数据结构
wells = [ [ [0, 0.4, 'pop'], [0.4, 1.2, 'sup'], [1.2, 2.4, 'gal'], [2.4, 3.2, 'grav40'], [3.2, 4, 'buz'] ], [ [0, 0.4, 'pop'], [0.4, 0.8, 'sup'], [0.8, 2.4, 'gal'], [2.4, 3.6, 'grav30'], [3.6, 4.4, 'buz'] ] ]
其中子列表格式为 [区间起始值, 区间结束值, 区间描述]。
需求
根据区间的对应层级关系,将第一个子列表与第二个子列表的区间结束值关联。
结果对比
- 错误匹配结果:
0.4 connects to 0.4 1.2 connects to 0.8 2.4 connects to 2.4 4 connects to 4.4
- 正确预期结果:
0.4 connects to 0.4 1.2 connects to 0.8 2.4 connects to 2.4 3.2 connects to 3.6 4 connects to 4.4
原尝试代码
wells = [ [ [0, 0.4, 'pop'], [0.4, 1.2, 'sup'], [1.2, 2.4, 'gal'], [2.4, 3.2, 'grav40'], [3.2, 4, 'buz'] ], [ [0, 0.4, 'pop'], [0.4, 0.8, 'sup'], [0.8, 2.4, 'gal'], [2.4, 3.6, 'grav30'], [3.6, 4.4, 'buz'] ] ] def find_matching_points_all(list1, list2): matching_points = [] for point1 in list1: for point2 in list2: if point1[2] == point2[2]: matching_points.append((point1[1], point2[1])) break return matching_points matching_points = find_matching_points_all(wells[0], wells[1]) for pair in matching_points: print(f"{pair[0]} connects with {pair[1]}") print()
问题分析与解决方案
原代码问题
- return缩进错误:
return matching_points放在了外层for循环内部,导致循环仅执行一次就返回结果,只能得到第一个匹配项。 - 匹配逻辑错误:仅通过描述完全相同来匹配区间,忽略了同位置的区间(如
grav40和grav30)属于对应层级,需要关联结束值的需求。
修正代码
wells = [ [ [0, 0.4, 'pop'], [0.4, 1.2, 'sup'], [1.2, 2.4, 'gal'], [2.4, 3.2, 'grav40'], [3.2, 4, 'buz'] ], [ [0, 0.4, 'pop'], [0.4, 0.8, 'sup'], [0.8, 2.4, 'gal'], [2.4, 3.6, 'grav30'], [3.6, 4.4, 'buz'] ] ] def find_matching_points_all(list1, list2): matching_points = [] # 按位置一一配对两个列表的区间(区间按深度顺序排列) for point1, point2 in zip(list1, list2): matching_points.append((point1[1], point2[1])) return matching_points matching_points = find_matching_points_all(wells[0], wells[1]) for pair in matching_points: print(f"{pair[0]} connects to {pair[1]}")
说明
- 两个井的区间列表均按深度从浅到深排列,使用
zip函数按位置一一配对区间,确保所有对应层级的结束值都能关联。 - 修正了
return的缩进问题,确保遍历完所有区间后再返回结果。运行后即可得到预期的正确输出。
内容的提问来源于stack exchange,提问作者Tommy Vercetti
相关产品推荐
相关产品推荐

