Home > Backend Development > Python Tutorial > How Can I Sort One List While Maintaining the Original Order of a Parallel List in Python?

How Can I Sort One List While Maintaining the Original Order of a Parallel List in Python?

Mary-Kate Olsen
Release: 2024-12-10 06:54:14
Original
723 people have browsed it

How Can I Sort One List While Maintaining the Original Order of a Parallel List in Python?

Maintaining Original Positions While Sorting a Parallel List

In the scenario where you have parallel lists and desire to sort one list while rearranging the other in a synchronized manner, a robust solution exists. Utilizing the "decorate, sort, undecorate" approach simplifies the process, particularly with Python's built-in zip function.

The Pythonic solution entails creating a decorated zip object, followed by sorting it, and finally extracting the original lists from the sorted zip. This technique preserves the original positions of elements in both lists.

For example, given the lists:

list1 = [3, 2, 4, 1, 1]
list2 = ['three', 'two', 'four', 'one', 'one2']
Copy after login

Executing the following code:

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

Will produce:

list1 = [1, 1, 2, 3, 4]
list2 = ['one', 'one2', 'two', 'three', 'four']
Copy after login

However, if the lists are empty, this specific method will not function properly. Modifying it slightly can address this issue:

list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))
Copy after login

Python offers an alternative in-place sorting approach, which, although more verbose, may provide a slight performance boost for smaller lists:

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

In summary, while several approaches exist to solve this problem, the zip method offers a concise and efficient solution that maintains the original positions of elements throughout the sorting process.

The above is the detailed content of How Can I Sort One List While Maintaining the Original Order of a Parallel 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