Practical Applications of Custom Sorting
Custom sorting using lambda functions in Python has a wide range of practical applications. Here are a few examples:
Sorting a List of Dictionaries
Suppose you have a list of dictionaries representing a collection of products, and you want to sort the list based on the price of each product. You can use a lambda function as the key for the sorted()
function:
products = [
{"name": "Product A", "price": 25.99},
{"name": "Product B", "price": 19.99},
{"name": "Product C", "price": 35.50},
{"name": "Product D", "price": 12.75}
]
sorted_products = sorted(products, key=lambda x: x["price"])
print(sorted_products)
## Output: [{'name': 'Product D', 'price': 12.75}, {'name': 'Product B', 'price': 19.99}, {'name': 'Product A', 'price': 25.99}, {'name': 'Product C', 'price': 35.50}]
Sorting a List of Tuples by Multiple Criteria
You can also use lambda functions to sort a list of tuples based on multiple criteria. For example, let's say you have a list of student records, and you want to sort them first by their grade and then by their age:
students = [
("Alice", 18, 90),
("Bob", 20, 85),
("Charlie", 19, 92),
("David", 21, 88)
]
sorted_students = sorted(students, key=lambda x: (-x[2], x[1]))
print(sorted_students)
## Output: [('Charlie', 19, 92), ('David', 21, 88), ('Alice', 18, 90), ('Bob', 20, 85)]
In this example, the lambda function lambda x: (-x[2], x[1])
uses a tuple of two values as the key. The first value, -x[2]
, sorts the list in descending order by the student's grade, and the second value, x[1]
, sorts the list in ascending order by the student's age.
Sorting a List of Objects
You can also use lambda functions to sort a list of custom objects. Suppose you have a Person
class with name
, age
, and height
attributes, and you want to sort a list of Person
objects by their height:
class Person:
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
def __repr__(self):
return f"Person('{self.name}', {self.age}, {self.height})"
people = [
Person("Alice", 25, 170),
Person("Bob", 30, 180),
Person("Charlie", 35, 175),
Person("David", 40, 165)
]
sorted_people = sorted(people, key=lambda x: x.height)
print(sorted_people)
## Output: [Person('David', 40, 165), Person('Alice', 25, 170), Person('Charlie', 35, 175), Person('Bob', 30, 180)]
In this example, the lambda function lambda x: x.height
extracts the height
attribute from each Person
object, and the sorted()
function uses this as the key for sorting the list.
These are just a few examples of the practical applications of custom sorting using lambda functions in Python. By understanding how to use lambda functions for sorting, you can write more flexible and efficient code that meets your specific needs.