2

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.

developer1
  • 73
  • 1
  • 6

1 Answers1

1
arr = [4,7,2,5]
indices = [0,2,1,3]
arr2 = [arr[i] for i in indices]
print(arr2)
Suneesh Jacob
  • 806
  • 1
  • 7
  • 15
  • This sometimes doesn't give correct answers. Input: `indices = [2, 1, 4, 3, 0]` and `arr=[3, 1, 4, 1, 3]` gives me `[4 1 3 1 3]` but should give `[3 1 3 1 4]` – developer1 Nov 10 '21 at 18:25
  • 1
    @developer1 -- the issue could be your definition of indices is different from what is commonly meant. The usual meaning is the list comprehension in this answer. Did you have a different meaning? – DarrylG Nov 10 '21 at 18:32
  • @developer1 I don't understand how it would be `[3,1,3,1,4]`. Did you by chance mean to apply rearrangement with the indices twice? Or reversing the order? Because doing it twice or reversing the order of the array, seems to be giving the output that you're expecting. Can you show more examples of arrays and indices and the corresponding outputs that you're expecting from them? – Suneesh Jacob Nov 10 '21 at 18:39
  • 2
    Sorting by using this method `[x for _, x in sorted(zip(Y, X))]` described in https://stackoverflow.com/questions/6618515/sorting-list-based-on-values-from-another-list did solve it correctly provided in comments by Chris – developer1 Nov 10 '21 at 18:44
  • Sorry, maybe you misunderstood or I didn't explain it correctly, but `indices = [2, 1, 4, 3, 0]` and `arr=[3, 1, 4, 1, 3]` should be sorted so that `indices` in the end would be `[0,1,2,3,4]` and `arr` accordingly. – developer1 Nov 10 '21 at 18:50
  • @developer1 I see. Well, yea in such case the link in Chris's comment is probably the most efficient way to do it. Another way, perhaps not as efficient, is to use this: `list(list(zip(*sorted(zip(indices,arr))))[1])` – Suneesh Jacob Nov 10 '21 at 19:18