[英]Python : Merge three lists of tuples according the first element of the tuple to add the seconds elements
I have three lists of tuples of size 2 given by:我有三个大小为 2 的元组列表:
a1 = [(47, 100)]
a2 = [(47, 100), (0, 86), (4, 86)]
a3 = [(47, 100), (39, 90)]
I want to merge them and remove the duplicates according the first element of the tuples.我想合并它们并根据元组的第一个元素删除重复项。 With the second, we add them.第二个,我们添加它们。 So we should get所以我们应该得到
a = [(47, 300) , (0, 86), (4, 86), (39, 90)]
How can i do that?我怎样才能做到这一点?
Thank you谢谢
combined = a1 + a2 + a3
seen = set()
desired_output = [(a, b) for a, b in combined if not (a in seen or seen.add(a))]
EDIT: I missed the part of the question of summing up the numbers.编辑:我错过了总结数字的问题部分。 Sorry about that.对于那个很抱歉。 Here is my edited answer addressing that part:这是我针对该部分编辑的答案:
mydict = dict()
for a, b in combined:
if a in mydict:
mydict[a] += b
else:
mydict[a] = b
final_tuple = list(mydict.items())
Try:尝试:
a1 = [(47, 100)]
a2 = [(47, 100), (0, 86), (4, 86)]
a3 = [(47, 100), (39, 90)]
out = {}
for l in [a1, a2, a3]:
for x, y in l:
out[x] = out.get(x, 0) + y
out = list(out.items())
print(out)
Prints:印刷:
[(47, 300), (0, 86), (4, 86), (39, 90)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.