'How can I sort a list based on another list? [duplicate]

Say I have two lists: test (1st one which will be the sorted one), and sort (which is the sorting index of the other list):

test
[16, 44, 12, 43, 17, 22, 6, 20, 41, 21]

sort
[20, 40, 43, 41, 29, 2, 14, 27, 44, 16 42, 21, 3, 22, 9, 32, 17, 23, 1, 
 31, 24, 19, 10, 33, 25, 26, 5, 30, 12, 28, 18, 8, 6, 15, 7, 13, 11, 4] 

How can I sort test based on the matrix position? This would be my desired solution:

[20, 43, 41, 44, 16, 21, 22, 17, 12, 6] 

Edit: I see there are many alike questions like mine, I tried a solution from Sorting list based on values from another list, which is the following:

[x for _, x in sorted(zip(test, sort))]
[14, 43, 20, 29, 27, 16, 2, 44, 41, 40]

As it can be seen, this is not equal to my desired output as 20 should be on the first place.



Solution 1:[1]

You can do this with list comprehension or looping over the matrix element to check each iteration if it belongs in the test array.

Example using list comprehension:

test = [16, 44, 12, 43, 17, 22, 6, 20, 41, 21]
matrix = [20, 40, 43, 41, 29, 2, 14, 27, 44, 16]

result = [i for i in matrix if i in test]

Example with normal append:

test = [16, 44, 12, 43, 17, 22, 6, 20, 41, 21]
matrix = [20, 40, 43, 41, 29, 2, 14, 27, 44, 16]

result = []
other = []

for i in matrix:
    if i in test:
        result.append(i)

    # Edit: if you want to keep the remaining ones in default sorting
    else:
        other.append(i)
result.extend(other)

Edit: updated the for loop to append everything not in test to another array. When the result array extend() that one, they would be combined. If this is what you're looking for, the list comprehension example here will not give the expected result.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1