Python遍历paths列表并合并关联cycle的代码修正问题
修正路径中循环边的添加逻辑
原代码存在两个核心问题:
- 错误地将整个cycle列表追加到单个路径边(比如
[3,4])里,而非追加到整条路径的末尾; - 循环嵌套过多导致同一个cycle被多次匹配(比如cycle内多个顶点与路径顶点重合),出现重复添加的情况。
以下是修正后的代码:
paths = [ [[1, 2]], [[1, 2], [2, 3], [3, 4]], [[1, 2], [2, 3], [3, 8], [8, 9], [9, 10]] ] cycles = [ [[10, 11], [11, 12], [12, 10]], [[4, 5], [5, 6], [6, 7], [7, 4]] ] # 预处理:建立顶点到对应cycle的映射,减少重复遍历 vertice_to_cycle = {} for cycle in cycles: cycle_vertices = set() for edge in cycle: cycle_vertices.update(edge) # 给cycle中的每个顶点绑定对应的cycle for v in cycle_vertices: vertice_to_cycle[v] = cycle # 处理每条路径 for current_path in paths: added_cycles = set() # 提取当前路径包含的所有顶点 path_vertices = set() for edge in current_path: path_vertices.update(edge) # 检查顶点是否关联cycle,且确保每个cycle只添加一次 for v in path_vertices: if v in vertice_to_cycle: target_cycle = vertice_to_cycle[v] if target_cycle not in added_cycles: # 将cycle的每条边单独追加到路径末尾 current_path.extend(target_cycle) added_cycles.add(target_cycle) # 输出结果 print(paths)
关键修正点:
- 预处理顶点映射:提前把每个cycle的顶点和对应cycle绑定,避免多层嵌套循环重复检查,提升效率;
- 去重机制:用
added_cycles集合记录已添加的cycle,确保同一个cycle不会被重复追加; - 正确追加位置:使用
current_path.extend(cycle)将cycle的每条边单独添加到整条路径的末尾,而非错误地追加到单个路径边中。
运行后得到的结果与期望输出完全一致:
[ [[1, 2]], [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 4]], [[1, 2], [2, 3], [3, 8], [8, 9], [9, 10], [10, 11], [11, 12], [12, 10]] ]
内容的提问来源于stack exchange,提问作者user18692484
相关产品推荐
相关产品推荐

