Python中元组列表的自定义降序排序问题求助(要求O(n log n)时间复杂度)
Hey there! Let's work through your problem step by step—you're already on the right track, just a small tweak needed to get the exact sorting behavior you want.
First: Time Complexity Reassurance
Great question about O(n log n) time! Python's built-in list.sort() method uses the Timsort algorithm, which has an average and worst-case time complexity of O(n log n). No matter what key function you use, this time complexity holds true, so you can check that requirement off your list.
Fixing the Sorting Logic
Your original code only sorted by the first element of the tuple, which is why you weren't seeing the second element get sorted when the first elements matched. To fix this, you need to include both elements in your sorting key, and adjust the direction to get descending order for both.
Here are two straightforward solutions that will give you exactly the result you want:
Option 1: Use Negative Values in the Key
By negating both elements in the key, we can sort in ascending order (the default) which effectively gives us descending order for the original values:
A = [(17, 8), (17, 12), (7, 2), (9, 15), (9, 17), (1, 4), (3, 9), (12, 14)] A.sort(key=lambda x: (-x[0], -x[1])) print(A)
-x[0]ensures tuples with larger first elements come first-x[1]ensures that when first elements are equal, tuples with larger second elements come first
Option 2: Keep reverse=True with a Multi-Element Key
You can also keep using reverse=True by passing both elements as the key. The reverse flag will apply descending order to both parts of the key:
A = [(17, 8), (17, 12), (7, 2), (9, 15), (9, 17), (1, 4), (3, 9), (12, 14)] A.sort(reverse=True, key=lambda x: (x[0], x[1])) print(A)
- When
reverse=True, the sort will first compare the first elements in descending order - If first elements match, it will then compare the second elements in descending order
Result
Both options will produce your desired output:
[(17, 12), (17, 8), (12, 14), (9, 17), (9, 15), (7, 2), (3, 9), (1, 4)]
内容的提问来源于stack exchange,提问作者user15874067

