Home > Net >  Reordering a list in a given order
Reordering a list in a given order

Time:11-15

I want to reorder my list in a given order, For example I have a list of ['a', 'b', 'c', 'd', 'e', 'f', 'g'] this has an index of [0,1,2,3,4,5,6] and lets say the new ordered list would have an order of [3,5,6,1,2,4,0] which would result in ['d','f','g', 'b', 'c', 'e', 'a'].

How would you result in such code?

I thought of using for loop by doing the

 for i in range(Len(list))

and after that I thought go using append or creating a new list? maybe but I'm not sure if I'm approaching this right.

CodePudding user response:

All you need to do is iterate the list of indexes, and use it to access the list of elements, like this:

elems =  ['a', 'b', 'c', 'd', 'e', 'f', 'g']
idx =  [3,5,6,1,2,4,0]

result = [elems[i] for i in idx]
print(result)

Output:

['d', 'f', 'g', 'b', 'c', 'e', 'a']

CodePudding user response:

import numpy as np

my_list =  ['a', 'b', 'c', 'd', 'e', 'f', 'g']

def my_function(my_list, index):
    return np.take(my_list, index)

print(my_function(my_list, [3,5,6,1,2,4,0]))

Output: ['d' 'f' 'g' 'b' 'c' 'e' 'a']
  • Related