Python列表多分支路径生成:重复映射下的循环实现求助
列表匹配分支生成解决方案
问题背景
原有代码会直接在子列表上追加匹配到的元素,但当A中存在重复匹配项时,需要为每个匹配生成独立的分支路径,而非在同一个列表上多次追加。
原代码逻辑
existing_list = [[1, 2, 3, 4], [2, 3, 4]] A = [4,5, 6] B = [5,6, 7] for i in range(len(existing_list)): sublist = existing_list[i] for j in range(len(A)): if sublist[-1] == A[j]: sublist.append(B[j]) print(existing_list) # 输出: [[1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7]]
修改后输入
existing_list = [[1, 2, 3, 4], [2, 3, 4]] A = [4,4,5, 6] B = [5,6,6, 7]
期望输出
[[1, 2, 3, 4, 5, 6, 7],[1, 2, 3, 4, 6, 7], [2, 3, 4,5, 6, 7],[2, 3, 4, 6, 7]]
解决方案代码
existing_list = [[1, 2, 3, 4], [2, 3, 4]] A = [4,4,5, 6] B = [5,6,6, 7] result = [] # 遍历每个初始子列表,生成所有分支路径 for sublist in existing_list: # 用栈存储待扩展的路径,确保生成顺序符合期望 path_stack = [sublist.copy()] current_paths = [] while path_stack: current = path_stack.pop() # 找到所有与当前列表末尾元素匹配的A的索引 match_indices = [j for j in range(len(A)) if A[j] == current[-1]] if not match_indices: # 无匹配项,当前路径完成 current_paths.append(current) continue # 为每个匹配项生成新路径,压入栈中 for j in match_indices: new_path = current.copy() new_path.append(B[j]) path_stack.append(new_path) # 反转路径列表,让顺序与期望输出一致 current_paths.reverse() result.extend(current_paths) print(result)
逻辑说明
- 独立分支生成:不再修改原列表,为每个匹配项复制原列表生成新路径,避免分支互相污染。
- 迭代扩展路径:使用栈存储待扩展的路径,每次取出路径后检查末尾元素是否能匹配
A中的元素,若匹配则生成新路径继续扩展,直到无匹配项为止。 - 顺序调整:通过反转最终路径列表,保证输出顺序与期望一致。
内容的提问来源于stack exchange,提问作者iceman
相关产品推荐
相关产品推荐

