杰瑞科技汇

Python中sorted与lambda如何结合使用?

Of course! Let's break down sorted() with lambda in Python, from the basics to powerful use cases.

Python中sorted与lambda如何结合使用?-图1
(图片来源网络,侵删)

The Short Answer (TL;DR)

A lambda function is a small, anonymous, one-line function. You use it with sorted() to provide a custom sorting rule.

# A list of dictionaries
people = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35}
]
# Sort the list of dictionaries by the 'age' key using a lambda
sorted_people = sorted(people, key=lambda person: person['age'])
print(sorted_people)
# Output:
# [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]

The Detailed Explanation

The sorted() Function

First, let's understand the sorted() function itself.

  • What it does: It takes any iterable (like a list, tuple, etc.) and returns a new sorted list. The original list is not modified.
  • Syntax: sorted(iterable, key=None, reverse=False)
    • iterable: The list or other collection you want to sort.
    • reverse: A boolean. If True, the list is sorted in descending order.
    • key: This is the most important part for our discussion. It's a function that is called on every element of the iterable before making comparisons.

The lambda Keyword

A lambda function is a special type of function in Python.

  • What it is: An anonymous (unnamed), small, one-line function.
  • Syntax: lambda arguments: expression
    • arguments: Like a regular function, it can take multiple arguments.
    • expression: A single expression that is evaluated and returned. You cannot have statements or multiple expressions in a lambda.

Example of a regular function vs. a lambda:

Python中sorted与lambda如何结合使用?-图2
(图片来源网络,侵删)
# Regular function
def get_age(person):
    return person['age']
# Equivalent lambda function
lambda person: person['age']

The lambda version is more concise and is perfect for simple operations that you only need to use once.

How sorted() and lambda Work Together

The key argument of sorted() expects a function. This function will be applied to each item in your list, and the sorted() function will use the result of that function to perform the comparison.

The process is:

  1. Take the first item from the list.
  2. Pass it to the key function (our lambda).
  3. The lambda returns a value (the "sort key").
  4. sorted() remembers this key.
  5. Repeat for all other items.
  6. sorted() sorts the original items based on the list of keys it generated.

Practical Examples

Let's explore common scenarios where this is incredibly useful.

Python中sorted与lambda如何结合使用?-图3
(图片来源网络,侵删)

Example 1: Sorting a List of Dictionaries

This is the most common use case. You have a list of complex objects (like dictionaries) and want to sort them by a specific value.

products = [
    {'id': 4, 'name': 'Laptop', 'price': 1200},
    {'id': 2, 'name': 'Mouse', 'price': 25},
    {'id': 1, 'name': 'Keyboard', 'price': 75},
    {'id': 3, 'name': 'Monitor', 'price': 300}
]
# Sort by price (ascending)
sorted_by_price = sorted(products, key=lambda p: p['price'])
print("Sorted by price (ascending):")
print(sorted_by_price)
# Output:
# [{'id': 2, 'name': 'Mouse', 'price': 25}, {'id': 1, 'name': 'Keyboard', 'price': 75}, {'id': 3, 'name': 'Monitor', 'price': 300}, {'id': 4, 'name': 'Laptop', 'price': 1200}]
# Sort by price (descending)
sorted_by_price_desc = sorted(products, key=lambda p: p['price'], reverse=True)
print("\nSorted by price (descending):")
print(sorted_by_price_desc)
# Sort by product name (alphabetically)
sorted_by_name = sorted(products, key=lambda p: p['name'])
print("\nSorted by name:")
print(sorted_by_name)

Example 2: Sorting a List of Tuples

By default, Python sorts a list of tuples by the first element. What if you want to sort by the second?

points = [(1, 5), (4, 1), (2, 8), (3, 0)]
# Default sort: by the first element of each tuple
print("Default sort:", sorted(points))
# Output: [(1, 5), (2, 8), (3, 0), (4, 1)]
# Sort by the second element using lambda
sorted_by_y = sorted(points, key=lambda point: point[1])
print("Sorted by Y-coordinate:", sorted_by_y)
# Output: [(3, 0), (4, 1), (1, 5), (2, 8)]

Example 3: Sorting a List of Custom Objects

If you have a class, you can use lambda to sort by an attribute of that class.

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    def __repr__(self):
        # This makes the print output nice
        return f"Employee({self.name}, ${self.salary})"
employees = [
    Employee('Charlie', 80000),
    Employee('Alice', 95000),
    Employee('Bob', 75000)
]
# Sort by salary
sorted_by_salary = sorted(employees, key=lambda emp: emp.salary)
print("Sorted by salary:", sorted_by_salary)
# Output: Employee(Bob, $75000), Employee(Charlie, $80000), Employee(Alice, $95000)

Example 4: Sorting by Multiple Criteria

This is where lambda really shines. Python's sorting is "stable," meaning that if two items have the same key, their original order is preserved. We can use this to sort by multiple criteria.

Let's sort a list of students first by grade (descending) and then by name (ascending).

students = [
    {'name': 'David', 'grade': 85},
    {'name': 'Charlie', 'grade': 92},
    {'name': 'Alice', 'grade': 85},
    {'name': 'Bob', 'grade': 92}
]
# Sort by grade (descending) and then by name (ascending)
# 1. Primary key: -student['grade'] (to sort descending)
# 2. Secondary key: student['name'] (to sort ascending)
sorted_students = sorted(students, key=lambda s: (-s['grade'], s['name']))
print("Sorted by grade (desc) then name (asc):")
print(sorted_students)
# Output:
# [
#   {'name': 'Bob', 'grade': 92},
#   {'name': 'Charlie', 'grade': 92},
#   {'name': 'Alice', 'grade': 85},
#   {'name': 'David', 'grade': 85}
# ]

How this works:

  • lambda s: (-s['grade'], s['name']) creates a tuple for each student.
  • For Bob, the tuple is (-92, 'Bob').
  • For Charlie, the tuple is (-92, 'Charlie').
  • Python compares these tuples element by element. Since -92 is the same for both, it moves to the next element: 'Bob' vs. 'Charlie'. 'Bob' comes first alphabetically.
  • The negative sign () is a clever trick to reverse the sort order for numbers without using reverse=True, which would be applied to the entire sort.

When to Use lambda vs. a def Function

Use lambda when... Use a def function when...
The function is simple and one line. The function is complex or has multiple lines of logic.
You only need to use it once. You plan to reuse the function in other parts of your code.
You're passing it as an argument (like to sorted, map, filter). The function's name makes your code more readable and self-documenting.
It requires docstrings or complex error handling.

For sorting, lambda is almost always the preferred choice because the logic is typically simple and self-contained.

分享:
扫描分享到社交APP
上一篇
下一篇