Understanding the Syntax of sorted(key=lambda: ...)` for Sorting Lists
The sorted() function in Python provides a concise way to sort a list. When sorting complex lists containing nested elements or tuples, you can customize the sorting using the key argument.
Lambda Function Syntax
The lambda function in the key argument is an anonymous function that specifies how to derive the sorting criterion for each element in the list. Its syntax is:
lambda input_variable(s): expression
For example:
<code class="python">f = lambda x: x + 1 f(10) # Returns 11</code>
Key Function in sorted()
In the context of sorted(), the key function specified by key=lambda is applied to each element in the list, and the results are used to determine the sorting order. The values returned by the lambda function act as surrogate values for sorting.
This mechanism allows you to sort the original list based on a specific property or characteristic of each element, rather than the elements themselves. For instance, you can sort a list of tuples by their second element:
<code class="python">mylist = [(3, 5, 8), (6, 2, 8), (2, 9, 4), (6, 8, 5)] sorted(mylist, key=lambda x: x[1]) # Output: [(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)] # Sorted by the second element of each tuple</code>
Boolean Values and Sorting
When the key function returns a boolean value, the sorting is based on the truthiness of the value. Elements with True values are placed before those with False values. However, note that the original order of elements with the same truthy value is retained:
<code class="python">mylist = [3, 6, 3, 2, 4, 8, 23] sorted(mylist, key=lambda x: x % 2 == 0) # Output: [3, 3, 23, 6, 2, 4, 8] # Odd numbers (False) come before even numbers (True) # Even numbers remain in their original order</code>
Using the Key for Complex Data Structures
The key function can be used with complex data structures to extract and compare specific attributes. For example, consider a list of dictionaries representing students:
<code class="python">students = [ {'name': 'John', 'age': 20}, {'name': 'Alice', 'age': 22}, {'name': 'Bob', 'age': 18}, ]</code>
To sort students by age using the sorted() function, you can use the key argument with a lambda function:
<code class="python">sorted(students, key=lambda x: x['age'])</code>
This lambda function extracts the age attribute from each dictionary and returns it, allowing the elements to be sorted based on age.
The above is the detailed content of How does the `sorted(key=lambda: ...)` function work for sorting lists in Python?. For more information, please follow other related articles on the PHP Chinese website!