Sort List by Another List in Python

Use the
zip()
andsorted()
Functions to Sort the List Based on Another List in Python 
Use the
NumPy
Module to Sort the List Based on Another List in Python 
Use the
more_itertools.sort_together
to Sort the List Based on Another List in Python
Generally, when we sort lists, we do it in ascending or descending order. However, we can sort a list based on the order of another list in Python.
We will learn how to sort a given list based on the values from another list in this article.
Use the zip()
and sorted()
Functions to Sort the List Based on Another List in Python
In this method, we will use the zip()
function to create a third object by combining the two given lists, the first which has to be sorted and the second on which the sorting depends.
We can then use the sorted()
function, which extracts the first elements of each pair of the given lists from the sorted and zipped list.
A = ["r", "s", "t", "u", "v", "w", "x", "y", "z"]
B = [0, 1, 1, 0, 1, 2, 2, 0, 1]
result_list = [i for _, i in sorted(zip(B, A))]
print(result_list)
Output:
['r', 'u', 'y', 's', 't', 'v', 'z', 'w', 'x']
Use the NumPy
Module to Sort the List Based on Another List in Python
In this method, we convert the lists into NumPy
arrays then apply the sorting algorithm to the lists. We sort the array on which the sorting depends using the argsort()
function and then use those values to filter the second array.
See the following example.
import numpy
A = ["r", "s", "t", "u", "v", "w", "x", "y", "z"]
B = [0, 1, 1, 0, 1, 2, 2, 0, 1]
A = numpy.array(A)
B = numpy.array(B)
inds = B.argsort()
sorted_a = A[B]
print(sorted_a)
Output:
['r' 's' 's' 'r' 's' 't' 't' 'r' 's']
To get the final data in a list, use the tolist()
function.
Use the more_itertools.sort_together
to Sort the List Based on Another List in Python
The more_itertools
module is an extension to the itertools
module. The sort_together
function returns the input iterables sorted together, with the list in key_list
argument as the priority for sorting.
For example,
from more_itertools import sort_together
X = ["r", "s", "t", "u", "v", "w", "x", "y", "z"]
Y = [0, 1, 1, 0, 1, 2, 2, 0, 1]
s = sort_together([Y, X])[1]
print(list(s))
Output:
['r', 'u', 'y', 's', 't', 'v', 'z', 'w', 'x']
We need to use the list()
function to get the final result as a list.