Home >Backend Development >Python Tutorial >How Can I Simultaneously Sort One List and Permute Another to Maintain Correspondence?
Problem:
Given two lists of items, known as list1 and list2, the goal is to sort the elements in list1 while simultaneously rearranging the elements in list2 to match the sorted order of list1. In other words, we want to maintain the correspondence between the elements in both lists.
Solution:
A widely adopted technique for this problem is the "decorate, sort, undecorate" idiom:
list1, list2 = zip(*sorted(zip(list1, list2)))
This code demonstrates the following steps:
Additional Considerations:
result1, result2 = zip(*sorted(zip(list1, list2), key=lambda x: x[0]))
The above is the detailed content of How Can I Simultaneously Sort One List and Permute Another to Maintain Correspondence?. For more information, please follow other related articles on the PHP Chinese website!