Python中将特定字符串列表转换为邻接列表的问题求助
问题:字符串列表转邻接列表时的解包错误
需要将类似['1 0', '2 0', '3 1 2']或[['1 0'], ['2 0'], ['3 1 2']]的字符串列表,转换为[[1, 0], [2,0], [3,1], [3,2]]格式的邻接列表。但因最后一个字符串包含多个数字,解包子列表时触发以下报错:
Traceback (most recent call last): File "/tmp/source.py", line 79, in <module> for dest, src in nlist: ValueError: too many values to unpack (expected 2)
现有代码
处理输入列表的代码:
linelist = ['1 0', '2 0', '3 1 2'] newlist = [] print("linelist1", linelist) for word in linelist: word = word.split(",") newlist.append(word)
执行后得到newlist: [['1 0'], ['2 0'], ['3 1 2']]
后续处理邻接关系的代码:
adj_list = {} nlist = [] for inner_list in newlist: values = [int(x) for x in inner_list[0].split()] # splits each sublist nlist.append(values) adj_list [values[1]] = values[0:] adj_list = defaultdict(list) for dest, src in nlist: adj_list[src].append(dest)
解决方案
核心问题是当拆分后的数字列表长度超过2时,直接用dest, src解包会失败。需要将第一个元素作为目标节点,后面的每个元素分别作为源节点,生成配对的子列表。
修正后的代码
from collections import defaultdict def process_input(input_list): # 统一输入格式:将双层列表转为单层字符串列表 if isinstance(input_list[0], list): input_list = [item[0] for item in input_list] return input_list def build_adjacency_list(input_list): processed_list = process_input(input_list) adjacency_list = [] adj_dict = defaultdict(list) for s in processed_list: nums = list(map(int, s.split())) if len(nums) < 2: continue dest = nums[0] # 遍历所有源节点,生成配对并更新邻接列表和字典 for src in nums[1:]: adjacency_list.append([dest, src]) adj_dict[src].append(dest) return adjacency_list, adj_dict # 测试示例 linelist1 = ['1 0', '2 0', '3 1 2'] result_list, result_dict = build_adjacency_list(linelist1) print("目标邻接列表:", result_list) # 输出: [[1, 0], [2, 0], [3, 1], [3, 2]] print("邻接字典:", result_dict) # 输出: defaultdict(<class 'list'>, {0: [1, 2], 1: [3], 2: [3]}) linelist2 = [['1 0'], ['2 0'], ['3 1 2']] result_list2, result_dict2 = build_adjacency_list(linelist2) print("双层输入的邻接列表:", result_list2) # 输出: [[1, 0], [2, 0], [3, 1], [3, 2]]
关键修正点
- 统一输入格式,兼容单层和双层字符串列表的输入
- 对每个拆分后的数字列表,提取第一个元素作为
dest,遍历后续所有元素作为src,逐个生成[dest, src]子列表,避免解包错误 - 同时生成目标格式的列表和常用的邻接字典,满足不同需求
- 跳过长度不足2的无效行,避免索引越界问题
内容的提问来源于stack exchange,提问作者dingoyum
相关产品推荐
相关产品推荐

