Python按电影类型生成边列表的代码问题求助
解决Python生成同类型电影边列表的问题
需求说明
现有一个以电影类型ID为键、对应类型电影标题列表为值的字典:
dictionary_title_withonegenere = { 28: ['Avatar: The Way of Water', 'Violent Night', 'Puss in Boots: The Last Wish'], 12: ['Avatar: The Way of Water', 'The Chronicles of Narnia: The Lion, the Witch and the Wardrobe'], 16: ['Puss in Boots: The Last Wish', 'Strange World'] }
需要生成边列表,关联同一类型下的任意两部电影,目标输出格式如下:
source target Avatar: The Way of Water Violent Night Avatar: The Way of Water Puss in Boots: The Last Wish Violent Night Puss in Boots: The Last Wish Avatar: The Way of Water The Chronicles of Narnia: The Lion, the Witch and the Wardrobe Puss in Boots: The Last Wish Strange World
原代码的问题
你提供的代码无法运行,主要问题包括:
- 缩进错误:Python对缩进要求严格,原代码的for循环存在多余缩进,会触发语法错误
- 变量滥用与未定义:将类型ID
genres[i]用作循环变量,覆盖了原有值;同时存在拼写错误sorce(应为source),以及未定义的变量y - 循环逻辑错误:嵌套循环的写法无法生成同一类型下所有两两电影的组合,逻辑完全错误
正确解决方案
使用itertools.combinations可以高效生成列表中所有不重复的两两元素组合,完美匹配需求。代码如下:
import itertools dictionary_title_withonegenere = { 28: ['Avatar: The Way of Water', 'Violent Night', 'Puss in Boots: The Last Wish'], 12: ['Avatar: The Way of Water', 'The Chronicles of Narnia: The Lion, the Witch and the Wardrobe'], 16: ['Puss in Boots: The Last Wish', 'Strange World'] } edges = [] # 遍历每个类型对应的电影列表 for movies in dictionary_title_withonegenere.values(): # 生成该类型下所有两两电影的组合 for source, target in itertools.combinations(movies, 2): edges.append({"source": source, "target": target}) # 按照目标格式打印结果 print(f"{'source':<30} {'target'}") for edge in edges: print(f"{edge['source']:<30} {edge['target']}")
代码说明
itertools.combinations(movies, 2):自动生成列表中所有长度为2的不重复组合,顺序与原列表一致,避免手动写多层循环的繁琐- 直接遍历字典的
values():无需手动维护类型ID列表,代码更灵活,新增类型时无需修改代码 - 字符串格式化
<30:让source列左对齐并占用30个字符宽度,保证输出格式与目标一致
内容的提问来源于stack exchange,提问作者Elly
相关产品推荐
相关产品推荐

