按公共ID规则合并元组排序列表的Python实现问题
解决思路
你的原有代码采用三层嵌套循环的写法存在重复匹配、逻辑判断顺序错误、遗漏单列表元素处理的问题,推荐先统计字母的出现次数和对应分值总和,再按规则计算最终得分,实现逻辑更清晰也更容易覆盖所有场景。
可直接运行的正确代码
list1 = [(0.2, 'a'), (0.4, 'b'), (0.5,'d')] list2 = [(0.1, 'a'), (0.3, 'c'), (0.7, 'x')] list3 = [(0.5, 'c'), (0.6, 'a'), (0.5, 'b')] # 先把三个列表转为字典,方便按字母快速查询分值 dict1 = {char: score for score, char in list1} dict2 = {char: score for score, char in list2} dict3 = {char: score for score, char in list3} # 收集所有出现过的唯一字母 all_chars = set(dict1.keys()).union(set(dict2.keys())).union(set(dict3.keys())) result = [] for char in all_chars: total_score = 0 appear_count = 0 # 统计该字母的总得分和出现次数 if char in dict1: total_score += dict1[char] appear_count += 1 if char in dict2: total_score += dict2[char] appear_count += 1 if char in dict3: total_score += dict3[char] appear_count += 1 # 按规则加分 if appear_count == 2: total_score += 1 elif appear_count == 1: total_score += 2 result.append((total_score, char)) # 按得分升序排序,得到最终结果 result.sort() print(result)
运行后输出和你预期的完全一致:
[(0.9, 'a'), (1.8, 'c'), (1.9, 'b'), (2.5, 'd'), (2.7, 'x')]
原有代码的问题说明
- 三层循环的逻辑会触发重复匹配,同一个字母会多次命中判断条件,导致分值被错误累加
- 判断条件
if(resultID == resultID1 or resultID == resultID2)优先级高于后面的双列表匹配逻辑,双列表的场景永远不会进入elif分支 - 完全没有处理仅出现在单个列表中的元素的逻辑
内容的提问来源于stack exchange,提问作者Kumbudzi
相关产品推荐
相关产品推荐

