1

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.

2 Answers 2

3

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'] 
Sign up to request clarification or add additional context in comments.

3 Comments

I hope the list comprehension syntax is clear, you can of course do it with a regular for-loop
Thank you so much for the instructions! I get how it works now. Just another question that continues from this. How would you reorder this list back to [a,b,c,d,e,f,g]? I tired reordering the mutated list using the index list that is provided but it doesn't rlly work that way. Would there be any way I could still use the given index list to reorder the list back?
^ @user14004788 You could post another follow-up question. But make it clear what's your "reorder the list back".
0
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'] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.