You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将任意顺序二元列表排序拼接为指定1行5列列表

路径拼接代码优化方案

原来的代码存在两个核心问题导致死循环:

  1. 依赖列表元素移动匹配逻辑,嵌套循环终止条件判断混乱,顺序不符合预期时会无限执行元素移动操作
  2. 路径拼接时没有处理同出度多分支的选择问题,可能提前选中通往终点0的边导致后续路径无法拼接

优化思路

完全不需要修改边的顺序,直接基于路径末尾节点匹配剩余可用边即可,核心逻辑如下:

  • 复制输入的边列表,避免修改原输入数据
  • 先找到首元素为5的起点边,初始化路径并移除该边
  • 循环拼接路径直到所有边用完:
    • 每次取路径末尾节点,匹配所有剩余可用边中首元素等于该节点的候选边
    • 如果存在多个候选边,优先选择不指向终点0的边(避免提前走到终点导致剩余边无法拼接)
    • 仅有一个候选边时直接选择,将边的第二个元素追加到路径后,移除该边
  • 最终返回拼接好的五元列表即可

优化后代码

def merge_line_parts(line_parts):
    # 复制输入边列表,避免修改原始数据
    edges = line_parts.copy()
    # 查找起点边(首元素为5)
    start_idx = None
    for i, (u, v) in enumerate(edges):
        if u == 5:
            start_idx = i
            break
    # 初始化路径
    path = [edges[start_idx][0], edges[start_idx][1]]
    del edges[start_idx]
    
    # 循环拼接直到所有边用完
    while edges:
        last_node = path[-1]
        # 筛选所有符合当前末尾节点的候选边
        candidates = []
        for idx, (u, v) in enumerate(edges):
            if u == last_node:
                candidates.append((idx, v))
        # 选择合适的边:多候选时不选通往终点0的边
        selected_idx, selected_v = None, None
        if len(candidates) > 1:
            for idx, v in candidates:
                if v != 0:
                    selected_idx = idx
                    selected_v = v
                    break
        else:
            selected_idx, selected_v = candidates[0]
        # 更新路径和剩余边
        path.append(selected_v)
        del edges[selected_idx]
    
    return [path]

# 测试所有排列场景
test_cases = [
    [[2, 1], [2, 0], [1, 2], [5, 2]],
    [[2, 1], [1, 2], [2, 0], [5, 2]],
    [[2, 1], [1, 2], [5, 2], [2, 0]],
    [[1, 2], [5, 2], [2, 0], [2, 1]]
]

for case in test_cases:
    all_lines = merge_line_parts(case)
    print("all_lines:", all_lines)

运行结果

所有测试用例均输出正确结果:

all_lines: [[5, 2, 1, 2, 0]]
all_lines: [[5, 2, 1, 2, 0]]
all_lines: [[5, 2, 1, 2, 0]]
all_lines: [[5, 2, 1, 2, 0]]

内容的提问来源于stack exchange,提问作者icecat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:57:03