Home > Backend Development > Python Tutorial > How Can I Sort One List While Maintaining Parallel Order in Another?

How Can I Sort One List While Maintaining Parallel Order in Another?

Mary-Kate Olsen
Release: 2024-12-07 15:03:15
Original
135 people have browsed it

How Can I Sort One List While Maintaining Parallel Order in Another?

Sorting Parallel Lists with Automatic Permutation

Problem Statement

Given two parallel lists of arbitrary data types, devise a method to sort one list while simultaneously rearranging the other list in the same order.

Solution

One common approach to address this problem involves the "decorate, sort, undecorate" idiom. Using Python's built-in zip function, we can efficiently combine the elements of both lists into tuples and sort these tuples based on the values from the first list. This sorted list of tuples can then be "undecorated" to obtain the desired sorted lists.

Implementation:

list1, list2 = zip(*sorted(zip(list1, list2)))
# Alternatively, for in-place sorting:
# tups = zip(list1, list2)
# tups.sort()
# list1, list2 = zip(*tups)
Copy after login

Advantages and Performance

This approach prioritizes simplicity and terseness, especially with the use of the zip function. However, for small lists, an in-place version might be slightly faster:

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

For larger lists, the one-line version could perform better in certain situations.

Alternative Approaches

As mentioned in the comments, other approaches exist, such as sorting indices or providing a custom key function to the sorting algorithm. These alternatives may be suitable if direct comparison of elements in the second list is problematic.

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