简体   繁体   English

Python:根据元组的第一个元素合并三个元组列表添加第二个元素

[英]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.

相关问题 Python将两个列表合并为两个元组的元组 - Python merge two lists into tuple of two tuples 元组列表列表,按第一个元素分组并添加第二个元素 - List of lists of tuples, group by first element and add second elements 根据 python 中的第一个元素合并两个列表列表 - Merge two list of lists according to first element in python 元组元素的元组列表? - lists of tuples by a tuple element? Python 元组:干净地删除前三个元素 - Python Tuples: remove the first three elements cleanly 如果第一个元组元素匹配,如何合并列表中的两个元组? - How to merge two tuples in a list if the first tuple elements match? 如何在两个不同的元组列表中与元组的第一个元素相交 - How to Intersect on first element of tuple in two different lists of tuples 比较Python中连续元组列表的第一个元素 - Comparing first element of the consecutive lists of tuples in Python 如果前两个元素相同,则在每个具有三个元素的元组列表中添加第三个元素 - Add third element in list of tuple having three elements each , if first two elements are Identical Python:在没有 itertools 的情况下合并元组内的列表或组合列表内的列表,因此没有元组对象 - Python: Merge lists within tuples OR combining lists within lists within lists without itertools and thus tuple object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM