Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a python method to re-order a list based on the provided new indices?

Tags:

python

numpy

Say I have a working list: ['a','b','c'] and an index list [2,1,0] which will change the working list to: ['c','b','a']

Is there any python method to do this easily (the working list may also be a numpy array, and so a more adaptable method is greatly preferred)? Thanks!

like image 997
Hailiang Zhang Avatar asked Dec 27 '22 07:12

Hailiang Zhang


1 Answers

  • ordinary sequence:

    L = [L[i] for i in ndx]
    
  • numpy.array:

    L = L[ndx]
    

Example:

>>> L = "abc"
>>> [L[i] for i in [2,1,0]]
['c', 'b', 'a']
like image 153
jfs Avatar answered Dec 31 '22 12:12

jfs