Reputation: 37
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.
Upvotes: 0
Views: 167
Reputation: 11193
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']]
Upvotes: 0
Reputation: 225
You can also use this:
C = list()
for i in A:
if B[0] in i or B[1] in i:
C.append(i)
Upvotes: 0
Reputation: 26039
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']]
Upvotes: 2
Reputation: 654
C = [y for y in A for x in B if x in y]
This should do the trick.
Upvotes: 0