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

如何在Python中将指定字符串嵌套列表转换为邻接表?

问题:将嵌套字符串列表转换为整数邻接表

输入的嵌套字符串列表:

[['1 0'], 
 ['2 0'], 
 ['3 1 2']]  

期望转换为整数类型的邻接表(注:原示例中3: 1,2不符合Python语法,以下为合法的邻接表结构):

{ 
    1: 0, 
    2: 0, 
    3: [1, 2] 
}

你当前尝试的代码:

newlist = []
for word in linelist:
    word = word.split(",")
    newlist.append(word)
print(newlist)

运行结果:

[['1 0'], 
 ['2 0'], 
 ['3 1 2']]  

解决方法

你的问题核心是用了错误的分隔符(逗号),且未完成字符串转整数、字典构建的关键步骤。以下是正确实现:

代码实现

linelist = [['1 0'], ['2 0'], ['3 1 2']]
adjacency_dict = {}

for sublist in linelist:
    # 取出子列表中的字符串,按空格分割成字符串片段
    str_parts = sublist[0].split()
    # 将所有字符串片段转换为整数
    num_parts = list(map(int, str_parts))
    # 第一个整数作为字典键,剩余部分作为值
    key = num_parts[0]
    values = num_parts[1:]
    # 若只有一个关联值则存单个整数,多个则存列表
    adjacency_dict[key] = values[0] if len(values) == 1 else values

print(adjacency_dict)

运行结果

{1: 0, 2: 0, 3: [1, 2]}

如果确实需要3: 1,2这类非语法格式(不推荐,不利于后续数据操作),可以将值转为字符串:

adjacency_dict[key] = values[0] if len(values) == 1 else ", ".join(map(str, values))

此时结果为:

{1: 0, 2: 0, 3: '1, 2'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:05:20