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

Python中Lambda函数传参原因解析:以sorted排序的key参数场景为例

Let's also break down the sorting rule this code enforces

The lambda returns a tuple that defines the sorting priority, which matches what you described: lowercase letters → uppercase letters → odd digits → even digits (your example input String123 outputs ginrtS132, which aligns perfectly with this order). Here's how the tuple's elements drive the sorting:

Tuples are compared element-by-element from left to right. Booleans are treated as 0 for False and 1 for True during comparison. Let's map each character type to its tuple values:

  • Lowercase letters: (False, False, False, True, <char>)
  • Uppercase letters: (False, False, True, False, <char>)
  • Odd digits: (True, False, False, False, <char>)
  • Even digits: (True, True, False, False, <char>)

When comparing these tuples:

  1. All letters have False (0) as the first element, while digits have True (1)—so letters come before digits.
  2. Among letters: lowercase has False (0) as the third element, uppercase has True (1)—so lowercase comes first.
  3. Among digits: odd digits have False (0) as the second element, even digits have True (1)—so odds come before evens.
  4. Within each group, the last element (x) sorts characters lexicographically (normal alphabetical/numerical order).

That's exactly why String123 becomes ginrtS132: lowercase letters sorted → uppercase S → odd digits 1,3 → even digit 2.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 17:17:38