Merging list of tuples in python

mhd

I need to merge two lists of tuples with expected result is some kind of intersection between two lists, I already have the DUMB solution.
List 1 has incomplete value in the last element of tuple.
List 2 has tuples that list 1 doesn't have and have tuples with complete value
Result...hmmm well, best described in example:

l1 = [('4',), ('6',)]
l2 = [('3', '1'), ('4', '23'), ('6', '34')]

#my dumb solution
def mymerge(l1,l2):
    l3 = []
    for x in l2:
        if x[0] in [ y[0] for y in l1 ]:
            l3.append(x)
    return l3

result = mymerge(l1,l2)
#result is what expected-> [('4','23'),('6','34')]

My question: What other solution beside my dumb solution ?
really curious...
Tnx

jmetz

A list comprehension should work:

result = [ l for l in l2 if (l[0],) in l1]

Similarly, you can use the inbuilt filter function

result = filter(lambda x: (x[0],) in l1, l2)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related