Reputation: 47
I am trying to work on a function that will take two lists, and create a new list as long as the first, and return True or False if each item in the list is found in the second list. I am also incorporating the use of numpy in the event I want to use a large list.
I tried the below but I was unable to produce the result that I wanted. Any assistance is appreciated.
import numpy as np
def a_is_in(a, b):
list1 = np.array(a)
list2 = np.array(b)
if list1 in list2:
return False
else:
return True
return
a = [3, 4, 8, 10, 11, 13]
b = [3, 6, 7, 13]
_is_in = a_is_in(a, b)
print(_is_in)
import numpy as np
def a_is_in(a, b):
list1 = np.array(a)
list2 = np.array(b)
result = lambda list1, list2: any(i in list2 for i in list1)
return result
a = [3, 4, 8, 10, 11, 13]
b = [3, 6, 7, 10, 13]
_is_in = a_is_in(a, b)
print(_is_in)
The returned result I am looking for is a list that looks like this: [True, False, False, True, False, True]
Thank you for your time.
Upvotes: 0
Views: 3229
Reputation: 1551
If you are using numpy you can use np.isin
function.
# arr1 and arr2 are your numpy arrays.
result = np.isin(arr1, arr2)
Upvotes: 2
Reputation: 23
I have tried to do this using a simple syntax (as a beginner I prefer not to go too far). But I think using a for loop for this can be a bit too heavy and there might be other simpler options.
def a_is_in(a, b):
result =[]
for i in range(0,len(a)):
if a[i] in b:
result.append(True)
else:
result.append(False)
return(result)
Upvotes: 1
Reputation: 39072
You can use simple list comprehension and use i in b
as the condition which will return either True
or False
First example
a = [3, 4, 8, 10, 11, 13]
b = [3, 6, 7, 13]
_is_in = [i in b for i in a]
print(_is_in)
# [True, False, False, False, False, True]
Second example
a = [3, 4, 8, 10, 11, 13]
b = [3, 6, 7, 10, 13]
_is_in = [i in b for i in a]
print(_is_in)
# [True, False, False, True, False, True]
Upvotes: 2