Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if list array contains element in another list

Given a list array a, and another list b and d. How can I check if list element in a exists in b (or another example, in d)? I know I can do it with a for loop of a element and check if each element is in b/d, but is there any API do it quickly?

 a = [[1,4], [17,33,2],[2,33]]

 b = [1,4,5,6]
 c = [[1,4]]

 d = [2,33]
 e = [[17,33,2],[2,33]]

Let put it this way, give list a and b, how can I write the loop below efficiently? Let say in one line using list comprehension.

        newls = []
        for sublist in a:
           newls.append(list(set(sublist).intersection(set(b))))  
like image 300
twfx Avatar asked Aug 21 '14 03:08

twfx


2 Answers

Like barmer mentioned in a comment above: finding the intersection of two lists can be done easily using list comprehension:

a = [[1,4], [17,33,2],[2,33]]
b = [[1,4], [1,2], [2,3], [2,33]]

print [x for x in a if x in b] # prints [[1, 4], [2, 33]]
like image 169
Nir Alfasi Avatar answered Sep 28 '22 06:09

Nir Alfasi


I doubt that this is what you really wanted, but it is what you've asked for, i.e. a one line list comprehension that produces the same result as your for loop:

newls = [list(set(sublist).intersection(set(b))) for sublist in a]

a = [[1,4], [17,33,2],[2,33]]
b = [1,4,5,6]
>>> c = [list(set(sublist).intersection(set(b))) for sublist in a]
>>> c
[[1, 4], [], []]

You probably don't want the empty lists in there, so:

>>> c = filter(None, [list(set(sublist).intersection(set(b))) for sublist in a])
>>> c
[[1, 4]]

Note that this does not give the expected result for the second case:

a = [[1,4], [17,33,2],[2,33]]
d = [2,33]
e = filter(None, [list(set(sublist).intersection(set(d))) for sublist in a])

>>> e
[[33, 2], [33, 2]]
like image 27
mhawke Avatar answered Sep 28 '22 07:09

mhawke