如何优雅实现按子列表字符串键合并列表并累加数值元素
问题:按子列表字符串元素合并求和两个嵌套列表
我希望按照子列表中的字符串元素对两个嵌套列表进行求和操作:相同字符串对应的数值相加,不同字符串则保留原数值和字符串。
示例输入
L1=[[2,"word1"],[1,"word2"],[3,"word3"]] L2=[[7,"word4"],[6,"word1"],[3,"word5"],[6,"word3"]]
期望输出
L3=[[8,"word1"],[1,"word2"],[9,"word3"],[7,"word4"],[3,"word5"]]
我已经通过while循环实现了该功能,但写法不够优雅,想了解更简洁的解决方案。以下是我目前的代码:
def sum_list(L1,L2): word1=[x[1] for x in L1] word2=[x[1] for x in L2] score1=[x[0] for x in L1] score2=[x[0] for x in L2] word3=[] L3=[] i=0 while i<len(word1): word3.append(word1[i]) if word1[i] not in word2: L3.append([score1[i],word1[i]]) else: L3.append([score1[i]+score2[word2.index(word1[i])],word1[i]]) i=i+1 i=0 while i<len(word2): if word2[i] not in word3: L3.append([score2[i],word2[i]]) i=i+1 return L3
简洁解决方案:利用字典分组求和
利用字典的键唯一性来分组,遍历列表累加对应字符串的数值,最后转换为目标格式即可,逻辑清晰且效率更高(字典查找为O(1),避免原代码中index的O(n)操作)。
方案1:基础字典实现(Python3.7+保留插入顺序)
def sum_list(L1, L2): score_map = {} # 处理L1的元素 for score, word in L1: score_map[word] = score_map.get(word, 0) + score # 处理L2的元素,累加数值 for score, word in L2: score_map[word] = score_map.get(word, 0) + score # 转换为目标嵌套列表格式 return [[value, key] for key, value in score_map.items()]
方案2:用defaultdict简化代码
from collections import defaultdict def sum_list(L1, L2): score_map = defaultdict(int) # 合并两个列表后遍历处理 for score, word in L1 + L2: score_map[word] += score return [[value, key] for key, value in score_map.items()]
上述两种方案在Python3.7及以上版本中,输出的列表顺序会和示例一致:先保留L1中元素的顺序,再添加L2中新增的元素。
内容的提问来源于stack exchange,提问作者Fitz
相关产品推荐
相关产品推荐

