如何在python中合并多个元组列表

时间:2015-07-13 20:32:42

标签: python list merge tuples

我有多个包含名称和计数的元组列表,我希望将它们的名称与它们各自的计数之和合并。例如,我有:

l1 = [('House', 3),('Backyard', 2),('Frontyard', 4)]
l2 = [('House', 10),('street', 7),('Frontyard', 4)]
l3 = [('Backyard', 10),('street', 7),('Frontyard', 4)]

我想得到:

result : [('house', 13),('Backyard', 12), ('street', 14), ('Frontyard', 12)]

1 个答案:

答案 0 :(得分:0)

只需使用一个字典进行累计......

result = {}
for L in l1, l2, l3:
    for key, value in L:
        result[key] = result.get(key, 0) + value

# convert to a list
result = list(result.items())