Home > Backend Development > Python Tutorial > How Can I Sort One List Based on the Values of a Corresponding List in Python?

How Can I Sort One List Based on the Values of a Corresponding List in Python?

Mary-Kate Olsen
Release: 2024-12-19 08:30:10
Original
611 people have browsed it

How Can I Sort One List Based on the Values of a Corresponding List in Python?

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))]
Copy after login

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]
Copy after login

Using the code:

Z = [x for _,x in sorted(zip(Y,X))]
print(Z)  # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
Copy after login

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])]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template