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']
Executing the following code:
list1, list2 = zip(*sorted(zip(list1, list2)))
Will produce:
list1 = [1, 1, 2, 3, 4] list2 = ['one', 'one2', 'two', 'three', 'four']
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))))
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)
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!