Python uses lambda expressions for list sorting
In Python, lambda expressions are a way to create anonymous functions, usually used when you need a simple function but don't want to formally define one. Using lambda expressions can easily sort lists, especially when sorting based on a specific condition or attribute.
Below is an example of using a lambda expression to sort a list:
Example
# Define a list containing tuples, each tuple contains name and age
people = [('Alice', 25), ('Bob', 20), ('Charlie', 30), ('David', 22)]
# Use lambda expression to sort by age
sorted_people = sorted(people, key=lambda x: x[1])
print(sorted_people)
people = [('Alice', 25), ('Bob', 20), ('Charlie', 30), ('David', 22)]
# Use lambda expression to sort by age
sorted_people = sorted(people, key=lambda x: x[1])
print(sorted_people)
Code analysis:
peopleis a list containing tuples, each tuple contains two elements: name and age.sorted()function is used to sort the list.keyparameter specifies the basis of sorting, here we uselambda x: x[1]to specify sorting by the second element of the tuple (i.e., age).lambda x: x[1]is an anonymous function that accepts a parameterx(i.e., each tuple in the list), and returnsx[1](i.e., the second element of the tuple, age).sorted_peopleis the sorted list.
Output result:
[('Bob', 20), ('David', 22), ('Alice', 25), ('Charlie', 30)]
It can be seen that the list has been sorted from smallest to largest by age.
Other extensions
Python3 Examples