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

如何将嵌套列表routes转换为指定格式的Python字典?

嵌套列表转指定字典的实现方案

原始数据

routes = [[0, 1, 9, 3, 0], [0, 2, 4, 7, 0], [0, 6, 0], [0, 8, 11, 5, 0], [0, 10, 0]]

目标格式

{
    0: [0, 1, 3, 9, 0],
    1: [0, 2, 4, 7, 0],
    2: [0, 6, 0],
    3: [0, 8, 11, 5, 0],
    4: [0, 10, 0]
}

实现代码

观察目标结构:仅第一个子列表交换了索引2和3的元素,其余子列表直接以原列表的索引作为字典键对应值。可以用以下两种方式实现:

方式一:分步处理

routes = [[0, 1, 9, 3, 0], [0, 2, 4, 7, 0], [0, 6, 0], [0, 8, 11, 5, 0], [0, 10, 0]]

# 复制并修改第一个子列表
first_route = routes[0].copy()
first_route[2], first_route[3] = first_route[3], first_route[2]

# 构建字典
result = {0: first_route}
for idx in range(1, len(routes)):
    result[idx] = routes[idx]

print(result)

方式二:字典推导式简化

routes = [[0, 1, 9, 3, 0], [0, 2, 4, 7, 0], [0, 6, 0], [0, 8, 11, 5, 0], [0, 10, 0]]

result = {
    0: routes[0][:2] + [routes[0][3], routes[0][2]] + routes[0][4:],
    **{i: routes[i] for i in range(1, len(routes))}
}

print(result)

输出结果

两种方式运行后都会得到符合要求的字典:

{0: [0, 1, 3, 9, 0], 1: [0, 2, 4, 7, 0], 2: [0, 6, 0], 3: [0, 8, 11, 5, 0], 4: [0, 10, 0]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:03:18