How to sort array by array of indices?

Viewed 357

I had a simple array of numbers arr = [4, 2, 7, 5]

I did some calculations with it, swapped some values and now I have two arrays:

The array itself arr = [4, 7, 2, 5]

And the array of indices for this array indices = [0, 2, 1, 3]

Each number indicates where the value of the array is in (value with index 1 swapped with value with index 2).

Having these two arrays, how could I return arr to it's initial state? So that arr[1] would be swapped with arr[2] as the indices array indicates.

P.S. I have numpy available to simplify things with arrays.

1 Answers
arr = [4,7,2,5]
indices = [0,2,1,3]
arr2 = [arr[i] for i in indices]
print(arr2)
Related