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)))
However, for larger lists, a more efficient in-place version exists:
tups = zip(list1, list2) tups.sort() list1, list2 = zip(*tups)
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]))
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!