Is there a python method to reorder a list based on provided new indexes?

Let's say I have a worklist: ['A', 'b', 's'] and an index list [2,1,0] which will change the worklist to: ['C', 'B', 'a']

Is there any python method to make this easy (a worklist can also be a numpy array, and therefore it is preferable to use a more adaptive method)? Thanks!

+4
source share
3 answers
  • usual 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'] 
+5
source

Converting my comment comment since closing this question:

As you mentioned numpy, here is the answer to this case:

For numeric data, you can do this directly with numpy arrays. Details here: http://www.scipy.org/Cookbook/Indexing#head-a8f6b64c733ea004fd95b47191c1ca54e9a579b5 p>

then the syntax

 myarray[myindexlist] 

For non-digital data, the most efficient way for long arrays that you read only once is the most likely:

 (myarray[i] for i in myindex) 

pay attention to expressions () for generator expressions instead of [] for list comprehension.

Read This: Generator Expressions and Understanding Lists

+3
source

This is very easy to do with numpy if you don't mind converting to numpy arrays:

 >>> import numpy >>> vals = numpy.array(['a','b','c']) >>> idx = numpy.array([2,1,0]) >>> vals[idx] array(['c', 'b', 'a'], dtype='|S1') 

To return to the list, you can:

 >>> vals[idx].tolist() ['c', 'b', 'a'] 
+2
source

Source: https://habr.com/ru/post/1393018/


All Articles