Fix Python – How can I reorder a list? [closed]

Question

Asked By – Niyaz

Given an arbitrary array of size n, I’d like to reorganize the elements of the array based on the array’s discrete indices.

Python example:

# Unique array of size n
[ "a", "b", "c", "d", "e", ... <n> ]

# Indices of array
[ 0, 1, 2, 3, 4, ... <index_of_n> ]

# Desired re-organization function 'indexMove'
indexMove(
    [ "a", "b", "c", "d", "e", ... <n> ],
    [ <index_of_n>, 4, 0, 2, 3, ... 1 ]
)

# Desired output from indexMove operation
[ <n>, "e", "a", "c", "d", ... "b" ]

What is the fastest way to perform this operation (achieving the smallest time complexity)?

Now we will see solution for issue: How can I reorder a list? [closed]


Answer

You can do it like this

mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist)         # prints: ['d', 'c', 'a', 'b', 'e']

This question is answered By – AJ.

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0