我尝试将多个列表合并到一个列表中,必须将具有相同元组键的值添加到一起。
例如:
A = [ (1,2),(5,2) ]
B = [ (1,2),(5,5),(11,2) ]
预期结果:
result = [ (1,4),(5,7),(11,2) ]
答案 0 :(得分:3)
一旦你意识到用dict
c = dict(A)
for key, value in B:
c[key] = c.get(key, 0) + value
result = list(c.items())
答案 1 :(得分:1)
如果订单不重要,使用collections.Counter
是另一种选择:
In [21]: from collections import Counter
In [22]: A = [ (1,2),(5,2) ]
In [23]: B = [ (1,2),(5,5),(11,2) ]
In [24]: (Counter(dict(A)) + Counter(dict(B))).items() # list(...) for Python 3
Out[24]: [(1, 4), (11, 2), (5, 7)]