7

Let's say I have the following array:

a = [4,2,3,1,4]

Then I sort it:

b = sorted(A) = [1,2,3,4,4]

How could I have a list that map where each number was, ex:

position(b,a) = [3,1,2,0,4]

to clarify this list contains the positions not values)

(ps' also taking in account that first 4 was in position 0)

dspencer
  • 4,297
  • 4
  • 22
  • 43
user8920367
  • 95
  • 1
  • 5
  • You can use numpy's [argsort](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html) function. – blue_note Apr 01 '20 at 11:41

2 Answers2

13
b = sorted(enumerate(a), key=lambda i: i[1])

This results is a list of tuples, the first item of which is the original index and second of which is the value:

[(3, 1), (1, 2), (2, 3), (0, 4), (4, 4)]
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    I might be tempted to take it one step further and unpack (if tuples are okay), eg: `orig_pos, b = zip(*sorted(enumerate(a), key=lambda i: i[1]))` – Jon Clements Apr 01 '20 at 11:42
  • Sure, if the idea is to have two separate lists; but IMO it usually makes more sense to keep data together which belongs together. – deceze Apr 01 '20 at 11:43
  • Yup... all depends... just throwing it out there :) – Jon Clements Apr 01 '20 at 11:44
2
def position(a):
    return sorted(range(len(a)), key=lambda k: a[k])
Sławomir Lenart
  • 7,543
  • 4
  • 45
  • 61