I have 2 arrays. I want to get rid of elements in array n1 if the element exists in array n2. I already have a solution, but it is not so efficient since it uses a for loop and I want to see if there is a faster way. The code concept that works is like below
n1 = [1, 2, 3, 4, 5]
n2 = [2, 3, 5]
#if n1 has an element that is in n2, then get rid of it.
for idx in range(len(n1)):
if(any(x in n1 for n2):
n1[idx] = []
output : n1 = [1,4]
The code is not 100% perfect, but that is the idea. Is there a way to achieve this without using the for loop? I am doing web scraping NN right now, and data is getting pretty heavy.
CodePudding user response:
Another way for it:
Sets:
n1 = list(set(n1).difference(n2))
Sets:
n1 = list(set(n1) - set(n2))
List comprehension:
n1 = [i for i in n1 if i not in n2]
CodePudding user response:
This is without a for loop, but it is still has an O(n) runtime, but this is about as good as you will be able to get.
n1 = [1, 2, 3, 4, 5]
n2 = [2, 3, 5]
set1 = set(n1)
print(set1.symmetric_difference(n2))
Output:
{1,4}