Determine the shuffled indices of two lists/arrays

后端 未结 6 599
野的像风
野的像风 2021-01-18 16:03

As a challenge, I\'ve given myself this problem:

Given 2 lists, A, and B, where B is a shuffled version of A, the idea is to figure out the shuffled indices.

6条回答
  •  悲哀的现实
    2021-01-18 16:24

    As mentioned in my question, I was able to solve this using a dictionary. I store the indices in a dict and then use a list comprehension to pop them out:

    A = [10, 40, 30, 2]
    B = [30, 2, 10, 40]
    
    idx = {}
    for i, l in enumerate(A):
        idx.setdefault(l, []).append(i)
    
    res = [idx[l].pop() for l in B]
    print(res)
    

    Output:

    [2, 3, 0, 1]
    

    This is better than the obvious [A.index(x) for x in B] because it is

    1. linear
    2. handles duplicates gracefully

提交回复
热议问题