Deriving the position of elements before sorting and sorting one-dimensional arrays in ascending order in python

Asked 2 years ago, Updated 2 years ago, 24 views

I would like to sort the 1D array in ascending order with python, and also derive the position of the elements before sorting.
With the sort function, I don't think the position of the previous element will remain, so I'm in trouble.

 li = [22, 50, 30, 46, 25, 12, 18, 19]

After Derivation

 li1 = [12, 18, 19, 22, 25, 30, 46, 50]
li2 = [5,6,7,0,4,2,3,1]

I would like to ask for the above results.Thank you for your cooperation.

python

2022-09-30 20:21

2 Answers

If you pack it in one line

 li1,li2 = [list(l)for lin zip(*sorted(zip(li,range(len(li)))))]

So what do you think? zip() adds the array location to each element, then sorts it into two parts: unzip.For "unzip"
https://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python-inverse-of-zip
I used zip(*zip) as a reference.The answer I'm looking for is not a tuple, but a list, so it's even more complicated, but without it

li1,li2 = zip(*sorted(zip(li,range(len(li)))))

That's it.

Either way, I think it would be easier to use without unzip depending on the purpose.


2022-09-30 20:21

>>li1, li2=sorted(li), sorted(range(len(li)) , key=lambdak:li[k])


2022-09-30 20:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.