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

Use a listcomprehension that checks if any of the elements in
B
is inA
: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']]

C = [y for y in A for x in B if x in y]
This should do the trick.

You can also use this:
C = list() for i in A: if B[0] in i or B[1] in i: C.append(i)

You can also use set intersection to check if there is any element in common between the element
e
(sublist) ofA
andb
defined asset(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']]