How to pin two lists of tuples in python

I have two lists of tuples, for example:

a = [(1,2,3),(4,5,6),(7,8,9)]
b = [(1,'a'),(4,'b'),(7,'c')]

The first element of each tuple in and b is mapped, I want to get a list like this:

merged = [(1,2,3,'a'),(4,5,6,'b'),(7,8,9,'c')]

Maybe I will have another list like:

c = [(1,'xx'),(4,'yy'),(7,'zz')]

and merging it into a "merged" list later, I tried "zip" and "map", which are not suitable for this case.

+3
source share
4 answers
def merge(a,b):
    for ax, (first, bx) in zip(a,b):
        if ax[0] != first:
            raise ValueError("Items don't match")
        yield ax + (bx,)

print list(merge(a,b))
print list(merge(merge(a,b),c))
+5
source
>>> a = [(1,2,3),(4,5,6),(7,8,9)]
>>> b = [(1,'a'),(4,'b'),(7,'c')]
>>> 
>>> [x + (z,) for x, (y, z) in zip(a, b)]
[(1, 2, 3, 'a'), (4, 5, 6, 'b'), (7, 8, 9, 'c')]

to check if the first elements match,

>>> [x + y[1:] for x, y in zip(a, b) if x[0] == y[0]]
+7
source
>>> [a[i]+(k,) for i,(j, k) in enumerate(b)]
[(1, 2, 3, 'a'), (4, 5, 6, 'b'), (7, 8, 9, 'c')]

Using timeit, this is the fastest published solution to return a merged list.

+1
source
[ (x,y,z,b[i][1]) for i,(x,y,z) in enumerate(a) if x == b[i][0] ]

This ensures that the values ​​are consistent and combined.

0
source

All Articles