Select sublist if element present in second list

I have two lists:

A = [['67', '75', 'X'], ['85','72', 'V'], ['1','2', 'Y'],  ['3','5', 'X', 'Y']]
B = ['X', 'Y']

I want to create a third list, C, that have the sublists of A which have the elements defined on B (an / or).

C = [[67', '75', 'X'],['1','2', 'Y'],  ['3','5', 'X', 'Y']]

I have tried:

C = [i for i in B if i in A]

But it didn't work, I get an empty C list. Please let me know what would be the best approach to obtain C.

4 answers

  • answered 2019-03-13 18:03 Austin

    Use a list-comprehension that checks if any of the elements in B is in A:

    A = [['67', '75', 'X'], ['85','72', 'V'], ['1','2', 'Y'], ['3','5', 'X', 'Y']]
    B = ['X', 'Y']
    
    C = [x for x in A if any(y in x for y in B)]
    # [['67', '75', 'X'], ['1', '2', 'Y'], ['3', '5', 'X', 'Y']]
    

  • answered 2019-03-13 18:04 Ashish kulkarni

    C = [y for y in A for x in B if x in y]
    

    This should do the trick.

  • answered 2019-03-13 18:04 Jacob

    You can also use this:

    C = list()
    for i in A:
        if B[0] in i or B[1] in i:
            C.append(i)
    

  • answered 2019-03-14 10:23 iGian

    You can also use set intersection to check if there is any element in common between the element e (sublist) of A and b defined as set(B).

    So,

    b = set(B)
    C = [ e for e in A if b.intersection(set(e)) ]
    
    #=> [['67', '75', 'X'], ['1', '2', 'Y'], ['3', '5', 'X', 'Y']]