Check if the list array contains an item in another list

Given the array of list a and another list of b and d. How to check if a list item exists in in b (or another example, in d)? I know I can do this with a for loop for an element and check if every element is in b / d, but is there any API to do this 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's just say list a and b, how can I write a loop below efficiently? Let them speak on the same line using list comprehension.

  newls = [] for sublist in a: newls.append(list(set(sublist).intersection(set(b)))) 
+5
source share
4 answers

I doubt that this is what you really wanted, but this is what you asked for, i.e. A one-page 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 need empty lists, 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]] 
+3
source

Like the bartender mentioned in the comment above: finding the intersection of two lists is easy using the 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]] 
+2
source

If you want compact code, not speed, you can use a set of APIs and this will tell you if there is an element that is in a, b and c at the same time (and tell you which ones)

 len(set(sum(a,[])) & set(b) & set(c).is_empty())>0 

This is not so bad because intersecting sets is efficient, but the sum function is not, so you can optimize the sum (a, []) bit by any of the methods suggested in Creating a flat list from a list of lists in Python

Also, if you only need to know if there is a common element, and not know all the elements that exist together, you can optimize it further, and you will have to implement a more dirty and more dirty code.

+1
source

Check if the list (dictionary) contains an element in another list

 a = [{'id':1,'val':4},{'id':17,'val':33},{'id':2,'val':33}] b = [1,4,5,6,17] print([x for x in a if x['id'] in b]) 

Demo

Check and get a specific value if the list (dictionary) contains an item in another list

 a = [{'id':1,'val':4,'code':'008'},{'id':17,'val':33,'code':'005'},{'id':2,'val':33}] b = [1,4,5,6,17] print([x['val'] for x in a if x['id'] in b]) 

Demo

0
source

Source: https://habr.com/ru/post/1200800/


All Articles