pythonarrayssortingreorderlist

How can I reorder a list?


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)?


Solution

  • 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']