Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sort array by another positions array

Assume I have two arrays, the first one containing int data, the second one containing positions

a = [11, 22, 44, 55]

b = [0, 1, 10, 11]

i.e. I want a[i] to be be moved to position b[i] for all i. If I haven't specified a position, then insert a -1

i.e

sorted_a = [11, 22,-1,-1,-1,-1,-1,-1,-1,-1, 44, 55]
            ^   ^                            ^   ^
            0   1                            10  11

Another example:

a = [int1, int2, int3]

b = [5, 3, 1]

sorted_a = [-1, int3, -1, int2, -1, int1]

Here's what I've tried:

def sort_array_by_second(a, b):

   sorted = []

   for e1 in a:
      sorted.appendAt(b[e1])

  return sorted

Which I've obviously messed up.

like image 514
Mark Kennedy Avatar asked Dec 02 '25 11:12

Mark Kennedy


1 Answers

Something like this:

res = [-1]*(max(b)+1)   # create a list of required size with only -1's

for i, v in zip(b, a):
    res[i] = v 

The idea behind the algorithm:

  1. Create the resulting list with a size capable of holding up to the largest index in b
  2. Populate this list with -1
  3. Iterate through b elements
  4. Set elements in res[b[i]] with its proper value a[i]

This will leave the resulting list with -1 in every position other than the indexes contained in b, which will have their corresponding value of a.

like image 182
Paulo Bu Avatar answered Dec 04 '25 00:12

Paulo Bu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!