Sorting Lists Using Corresponding Values from a Parallel List
You have a list of strings (X) and a corresponding list of integers (Y). Your goal is to sort the strings in list X based on the values in list Y. In this case, the desired output is:
["a", "d", "h", "b", "c", "e", "i", "f", "g"]
Shortest Code Solution
The shortest way to achieve this is using a list comprehension with the sorted and zip functions:
[x for _, x in sorted(zip(Y, X))]
This code zips the lists together and then sorts them based on the first elements (the integers from list Y). It then extracts the second elements (the strings from list X) from the sorted list.
Example
Consider the lists:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Using the code:
Z = [x for _,x in sorted(zip(Y,X))] print(Z) # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
General Solution
A more general solution is to use the sorted function with a custom key function:
[x for _, x in sorted(zip(Y, X), key=lambda pair: pair[0])]
Here, the key function extracts the first element from each pair in the zipped list, allowing you to sort based on the integers in list Y.
The above is the detailed content of How Can I Sort One List Based on the Values of a Corresponding List in Python?. For more information, please follow other related articles on the PHP Chinese website!