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 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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With