Home >Backend Development >Python Tutorial >How Can I Simultaneously Sort One List and Permute Another to Maintain Correspondence?

How Can I Simultaneously Sort One List and Permute Another to Maintain Correspondence?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 20:51:12217browse

How Can I Simultaneously Sort One List and Permute Another to Maintain Correspondence?

Simultaneously Sorting and Permuting Parallel Lists

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:

  1. zip(list1, list2) creates pairs of corresponding elements from both lists, effectively "decorating" each element with its companion from the other list.
  2. sorted(zip(list1, list2)) sorts the pairs based on the first element (from list1).
  3. zip(*...) "undecorates" the sorted pairs, producing the sorted list1 and the matching, permuted list2.

Additional Considerations:

  • The provided solution interprets equal elements in list1 by comparing their corresponding elements in list2. If this comparison is undesirable or computationally expensive, consider using the alternative key function:
result1, result2 = zip(*sorted(zip(list1, list2), key=lambda x: x[0]))
  • Handling empty input lists is essential. If your input lists might be empty, ensure that you have appropriate error handling or special cases to prevent errors.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn