sorted函数key参数中lambda表达式的工作原理及参数赋值疑问
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 yourrowslist 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 argumentrto your lambda function. Important:risn’t the entirerowslist—it’s each individual dictionary in the list, one after another. - The lambda function takes that dictionary
rand returns the value associated with the'fname'key (like'Brian','David', etc.). sorted()collects all thesefnamevalues, sorts them alphabetically, then rearranges the original dictionaries to match the order of their sortedfnamevalues.
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

