Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Filter in tuples

I have two lists of tuples. I want a new list with every member of l2 and every member of l1 that does not begin with the same element from l2.

I used a for loop and my output is ok.

My question is: How can I use the filter function or a list comprehension?

def ov(l1, l2):

    l3=l1.copy()    
    for i in l2:

        for j in l1:

            if i[0]==j[0]:
                l3.pop(l3.index(j))

    print (l3+l2)            

ov([('c','d'),('c','e'),('a','b'),('a', 'd')], [('a','c'),('b','d')])

The output is:

[('c', 'd'), ('c', 'e'), ('a', 'c'), ('b', 'd')]
like image 844
Pedro Pinto Avatar asked Sep 02 '26 23:09

Pedro Pinto


2 Answers

If I understand correctly, this should be the straight forward solution:

>>> l1 = [('c','d'),('c','e'),('a','b'),('a', 'd')]                                                                               
>>> l2 = [('a','c'),('b','d')]                                                                                                    
>>>                                                                                                                               
>>> starters = set(x for x, _ in l2)                                                                                              
>>> [(x, y) for x, y in l1 if x not in starters] + l2                                                                             
[('c', 'd'), ('c', 'e'), ('a', 'c'), ('b', 'd')]

This can be generalized to work with longer tuples with extended iterable unpacking.

>>> starters = set(head for head, *_ in l2)                                                                                             
>>> [(head, *tail) for head, *tail in l1 if head not in starters] + l2                                                            
[('c', 'd'), ('c', 'e'), ('a', 'c'), ('b', 'd')]
like image 187
timgeb Avatar answered Sep 05 '26 16:09

timgeb


Here is an approach using filter:

from operator import itemgetter

f = itemgetter(0)
zval = set(map(itemgetter(0), l2))

list(filter(lambda tup: f(tup) not in zval, l1)) + l2

[('c', 'd'), ('c', 'e'), ('a', 'c'), ('b', 'd')]

Or:

def parser(tup):
    return f(tup) not in zval

list(filter(parser, l1)) + l2

[('c', 'd'), ('c', 'e'), ('a', 'c'), ('b', 'd')]
like image 39
gold_cy Avatar answered Sep 05 '26 16:09

gold_cy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!