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)
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)
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!