Home > other >  How keep in place elements in array which are in second array
How keep in place elements in array which are in second array

Time:10-13

I have two arrays and I need to create new array which include elements which are in first array have such as here:

array1 = [1,2,3]
array2 = [1,3,6,3,8,2,2,3,3]
my_func(arr1, arr2):
  ...
  return new_array

print(myfunc(array1, array2))

Output: [1,3,3,2,2,3,3]

CodePudding user response:

array1 = [1,2,3]
array2 = [1,3,6,3,8,2,2,3,3]


def my_func(arr1, arr2):
    checks = set(arr1)
    return list(filter(
        lambda item: item in checks,
        arr2
    ))


print(my_func(array1, array2))

CodePudding user response:

not clever or anything, but you could just loop through and only include values from array2 if they're in array1:

my_func(arr1, arr2):
  arr3 = []  
  for x in arr2:
    if x in arr1:
      arr3.append(x)
  return arr3

CodePudding user response:

You could answer this by looping around the array2 and checking if the each element is present in array1 if yes then append to new_array else go on with loop.

  1. Make a new array (In your case new_array);
  2. Loop around the array2.
  3. Inside the loop check if the element is present inside array.
  4. If present append to new_array.
  5. After loop end return the new_array.

If you are not able To understand above logic please refer to code below and try to understand from it.

array1 = [1,2,3]
array2 = [1,3,6,3,8,2,2,3,3]
def my_func(arr1, arr2):
    new_array = []
    for i in range(len):
        if(i in arr1):
            new_array.append(i)
    return new_array

print(my_func(array1, array2))
  • Related