Determine the shuffled indices of two lists/arrays

后端 未结 6 636
野的像风
野的像风 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:26

    We can make use of np.searchsorted with its optional sorter argument -

    sidx = np.argsort(B)
    out = sidx[np.searchsorted(B,A, sorter=sidx)]
    

    Sample run -

    In [19]: A = [10, 40, 30, 2, 40]
        ...: B = [30, 2, 10, 40]
        ...: 
    
    In [20]: sidx = np.argsort(B)
    
    In [21]: sidx[np.searchsorted(B,A, sorter=sidx)]
    Out[21]: array([2, 3, 0, 1, 3])
    

提交回复
热议问题