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

sorted函数key参数中lambda表达式的工作原理及参数赋值疑问

Understanding how key=lambda r: r['fname'] works in Python's sorted() function

Hey, great question—this is a super common point of confusion when first working with lambda functions and sorting in Python! Let’s break down exactly what’s happening here, step by step.

First, let’s clarify the role of the sorted() function: it’s designed to work with iterables (like your rows list of dictionaries). When you pass a key parameter to sorted(), you’re giving it a rule: "For every item in this list, run this function on the item, and use the result to determine the sort order of the original items."

Here’s the play-by-play of what happens with your code:

  • sorted() starts looping through each element in your rows list one at a time. Each element is a single dictionary (e.g., {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003}).
  • For each of these dictionary elements, sorted() automatically passes it as the argument r to your lambda function. Important: r isn’t the entire rows list—it’s each individual dictionary in the list, one after another.
  • The lambda function takes that dictionary r and returns the value associated with the 'fname' key (like 'Brian', 'David', etc.).
  • sorted() collects all these fname values, sorts them alphabetically, then rearranges the original dictionaries to match the order of their sorted fname values.

You don’t need to call the lambda manually because sorted() handles invoking it for every element in the iterable. The lambda is just a tiny, inline function that tells sorted() exactly which piece of data to use as the sorting "key."

To make it even more concrete, let’s walk through one iteration with your sample data:
When sorted() processes the first dictionary in rows ({'fname': 'Brian', ...}), it runs lambda r: r['fname'] with r set to that dictionary—so the lambda returns 'Brian'. For the next dictionary ({'fname': 'David', ...}), it returns 'David', and so on. sorted() then sorts these strings ('Big', 'Brian', 'David', 'John') and maps back to the original dictionaries to create the sorted list rows_by_fname.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:37:39