Search code examples
pythonlistrevert

Python how to revert the pattern of a list rearrangement


So I am rearranging a list based on an index pattern and would like to find a way to calculate the pattern I need to revert the list back to its original order.

for my example I am using a list of 5 items as I can work out the pattern needed to revert the list back to its original state.

However this isn't so easy when dealing with 100's of list items.

def rearrange(pattern: list, L: list):
    new_list = []
    for i in pattern:
        new_list.append(L[i-1])
    return new_list

print(rearrange([2,5,1,3,4], ['q','t','g','x','r']))

#['t', 'r', 'q', 'g', 'x']

and in order to set it back to the original pattern I would use

print(rearrange([3,1,4,5,2],['t', 'r', 'q', 'g', 'x']))
#['q', 't', 'g', 'x', 'r']

What I am looking for is a way to calculate the pattern "[3,1,4,5,2]" regarding the above example. whist running the script so that I can set the list back to its original order.

Using a larger example:

print(rearrange([18,20,10,11,13,1,9,12,16,6,15,5,3,7,17,2,19,8,14,4],['e','p','b','i','s','r','q','h','m','f','c','g','d','k','l','t','a','n','j','o']))
#['n', 'o', 'f', 'c', 'd', 'e', 'm', 'g', 't', 'r', 'l', 's', 'b', 'q', 'a', 'p', 'j', 'h', 'k', 'i']

but I need to know the pattern to use with this new list in order to return it to its original state.

print(rearrange([???],['n', 'o', 'f', 'c', 'd', 'e', 'm', 'g', 't', 'r', 'l', 's', 'b', 'q', 'a', 'p', 'j', 'h', 'k', 'i']))
#['e','p','b','i','s','r','q','h','m','f','c','g','d','k','l','t','a','n','j','o']

Solution

  • This is commonly called "argsort". But since you're using 1-based indexing, you're off-by-one. You can get it with numpy:

    >>> pattern
    [2, 5, 1, 3, 4]
    >>> import numpy as np
    >>> np.argsort(pattern) + 1
    array([3, 1, 4, 5, 2])
    

    Without numpy:

    >>> [1 + i for i in sorted(range(len(pattern)), key=pattern.__getitem__)]
    [3, 1, 4, 5, 2]