When working with multiple parallel lists, it can be necessary to sort one list while maintaining the corresponding order of elements in the other lists. To achieve this, we present two classic approaches.
This technique simplifies the task using Python's built-in zip function, which combines elements from multiple lists into tuples:
list1 = [3, 2, 4, 1, 1] list2 = ['three', 'two', 'four', 'one', 'one2'] list1, list2 = zip(*sorted(zip(list1, list2)))
After sorting the tuples by the first element (list1), the order is applied to both lists.
For increased speed, you can use an in-place sorting approach:
tups = zip(list1, list2) tups.sort() result1, result2 = zip(*tups)
This approach typically outperforms the one-line version for small lists but becomes comparable for larger lists due to Python's optimized zip routines.
list1 = [3, 2, 4, 1, 1] list2 = [num * num for num in list1] result1, result2 = zip(*sorted(zip(list1, list2), key=lambda x: x[0]))
The above is the detailed content of How Can I Sort Multiple Lists in Python While Maintaining Alignment?. For more information, please follow other related articles on the PHP Chinese website!