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

请求解析Python frequencySort函数中sorted方法的key参数lambda x: (count[x], -x)的含义

Understanding the key Parameter in sorted(): lambda x: (count[x], -x)

Great question—let's break down exactly what this lambda is doing in your frequencySort method. It's a clever way to apply two layers of sorting logic to your list, so let's unpack it step by step:

First, a quick reminder: count = collections.Counter(nums) creates a counter object that tracks how many times each number appears in nums. For example, if nums = [4,4,1,1,1,2], then count[4] = 2, count[1] = 3, and count[2] = 1.

Now, the lambda lambda x: (count[x], -x) returns a tuple for every element x in your list. Python's sorted() function uses these tuples to sort elements, comparing them from left to right:

1. First Priority: Sort by Frequency (Lowest to Highest)

The first value in the tuple is count[x], the frequency of the number x. Since sorted() defaults to ascending order:

  • Numbers that appear fewer times will be placed at the start of the list.
  • If two numbers have the same frequency, we use the second value in the tuple to break the tie.

2. Second Priority: Sort by Numerical Value (Highest to Lowest)

The second value is -x, the negative of the original number. Again, using ascending order for the tuple:

  • A larger original number will have a smaller negative value (e.g., -4 < -2).
  • Since smaller tuples come first in ascending sort, this means larger numbers will be placed before smaller ones when their frequencies are equal.

Example to Make It Clear

Let's use nums = [1,1,2,2,3] as a test case:

  • count will be {1:2, 2:2, 3:1}
  • Each element's key tuple looks like this:
    • 1 → (2, -1)
    • 1 → (2, -1)
    • 2 → (2, -2)
    • 2 → (2, -2)
    • 3 → (1, -3)
  • When sorted, the final list is [3, 2, 2, 1, 1]:
    • 3 is first because its frequency (1) is lower than 1 and 2 (both 2).
    • 2 comes before 1 because -2 < -1—so the tuple (2, -2) is smaller than (2, -1), and sorted() prioritizes smaller keys. This gives us the descending numerical order for elements with matching frequencies.

If you wanted to sort by highest frequency first instead, you'd just negate the frequency part: lambda x: (-count[x], -x). But as written, your function sorts from least frequent to most frequent, with ties broken by putting larger numbers first.

内容的提问来源于stack exchange,提问作者one_random_python_learner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:57:36