Can we get common elements in two arrays with loops and if condition?
#copy the members of 1st array that are present 2nd array to 3rd array
import array as ar
import numpy as np
a1=ar.array('i',range(10))
a2=ar.array('i',[2,3,5,8,9,11,12])
a3=np.intersect1d(a1, a2)
print(a3)
type(a3)
#output
[2 3 5 8 9]
numpy.ndarray
CodePudding user response:
Python list comprehension is a powerful thing:
a = [1, 2, 3, 4]
b = [3, 5, 4, 6]
c = [ x for x in a if x in b]
print(c)
# Output: [3, 4]
CodePudding user response:
There are two ways to do it. Lets take two arrays arr1 and arr2 and an empty array arr3.
arr1 = [i for i in range(1, 20)]
arr2 = [i for i in range(15, 25)]
arr3 = []
The conventional way would be to loop through the elements followed by an if statement that would check if the element is on the second array and append the element to the third array if the condition is satisfied.
arr3 = [i for i in arr1 if i in arr2]
Or you could convert the arrays into set and use intersection and convert them back.
arr3 = list(set(arr1).intersection(set(arr2)))
CodePudding user response:
With the help of set operators, I was able to get common elements in 2 arrays and returned to 3rd array.
#copy the members of 1st array that are present 2nd array to 3rd array
import array as ar
a1=ar.array('i',range(10))
a2=ar.array('i',[2,3,5,8,9,12,13,15])
a3=ar.array(a1.typecode,(set(a1)&set(a2)))
print(a3)
type(a3)
#output
array('i', [2, 3, 5, 8, 9])
array.array
``