You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中元组列表的自定义降序排序问题求助(要求O(n log n)时间复杂度)

Solution for Your Tuple Sorting Task

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:22:37