使用collections.Counter
>>> x1 = [('A', 3), ('B', 4), ('C', 5)]
>>> x2 = [('B', 4), ('C', 5), ('D', 6)]
>>> from collections import Counter
>>> c1 = Counter(dict(x1))
>>> c2 = Counter(dict(x2))
>>> c3 = c1 + c2
>>> c3.items()
dict_items([('A', 3), ('B', 8), ('C', 10), ('D', 6)])
只需为每个列表创建一个Counter,您可以通过将元组列表转换为中间字典来做到这一点。然后只需添加计数器。
要取回列表,只需调用计数器的 items 方法。从技术上讲,返回的是一个dict_items 对象,如果它真的很重要,它是一个list,那么只需调用c3.items() 上的列表,即list(c3.items())。
使用 groupby 和 heapq.merge 的替代 1 班轮。
from heapq import merge
from itertools import groupby
from operator import itemgetter
x1 = [('A', 3), ('B', 4), ('C', 5)]
x2 = [('B', 4), ('C', 5), ('D', 6)]
result = [(a, sum(t[1] for t in b)) for a, b in groupby(merge(x1, x2), key=itemgetter(0))]
print(result)
heapq.merge 大致相当于sorted(itertools.chain(*iterables))。它基本上提供了一个排序的、合并的元组列表,可以提供给 groupby。