Home > Backend Development > Python Tutorial > How Can I Efficiently Sort Two Parallel Lists in Python While Maintaining Synchronization?

How Can I Efficiently Sort Two Parallel Lists in Python While Maintaining Synchronization?

Barbara Streisand
Release: 2024-12-11 14:49:12
Original
570 people have browsed it

How Can I Efficiently Sort Two Parallel Lists in Python While Maintaining Synchronization?

Sorting Lists with Permutation of Parallel List

Given two parallel lists, one can be sorted while reordering the other in sync. This is achieved by sorting the first list and using the indices of the reordered elements to rearrange the second list.

One common approach is the "decorate, sort, undecorate" idiom, which zips the two lists, sorts them based on the first list, and then unzips the result. Using Python's zip function, this can be concisely implemented as follows:

list1, list2 = zip(*sorted(zip(list1, list2)))
Copy after login

However, for larger lists, a more efficient in-place version exists:

tups = zip(list1, list2)
tups.sort()
list1, list2 = zip(*tups)
Copy after login

For lists containing non-comparable elements, sorting indices using lambda functions can be employed. Alternatively, a key function can be provided to the sort to avoid comparing the second list's elements:

result1, result2 = zip(*sorted(zip(list1, list2), key=lambda x: x[0]))
Copy after login

Empty inputs should be handled separately, and one should be aware that the in-place version may be slightly faster, especially for small lists.

The above is the detailed content of How Can I Efficiently Sort Two Parallel Lists in Python While Maintaining Synchronization?. For more information, please follow other related articles on the PHP Chinese website!

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