杰瑞科技汇

Python lambda与list如何结合使用?

Of course! Let's break down Python's lambda functions and how they are used with lists, a very common and powerful combination.

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

What is a Lambda Function?

A lambda function is a small, anonymous (unnamed) function in Python. You can think of it as a quick, one-line function.

Syntax:

lambda arguments: expression
  • lambda: The keyword that defines an anonymous function.
  • arguments: Input(s) to the function, just like a regular function.
  • A separator between arguments and the expression.
  • expression: A single expression that is evaluated and returned. You cannot have statements or multiple expressions in a lambda.

Comparison: Regular Function vs. Lambda

Let's say we want a function that squares a number.

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

Regular Function:

def square(x):
    return x * x
print(square(5))  # Output: 25

Equivalent Lambda Function:

# The lambda function itself doesn't have a name
square_lambda = lambda x: x * x
print(square_lambda(5))  # Output: 25

Key Differences:

  • No Name: Lambdas are anonymous, though you can assign them to a variable (like square_lambda above).
  • Single Expression: A lambda can only contain a single expression. def can have multiple lines, loops, if statements, etc.
  • Conciseness: Lambdas are designed for short, simple operations.

Using Lambda with Lists

The real power of lambda shines when you use it as an argument for functions that operate on lists, especially map(), filter(), and sorted().

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

A. map(function, iterable)

The map() function applies a given function to every item of an iterable (like a list) and returns a map object (which is an iterator). You usually convert it back to a list.

Example: Square every number in a list.

numbers = [1, 2, 3, 4, 5]
# Using a regular function with map
def square(x):
    return x * x
squared_numbers_map = list(map(square, numbers))
print(squared_numbers_map)  # Output: [1, 4, 9, 16, 25]
# Using a lambda with map (more concise)
squared_numbers_lambda = list(map(lambda x: x * x, numbers))
print(squared_numbers_lambda)  # Output: [1, 4, 9, 16, 25]

B. filter(function, iterable)

The filter() function constructs an iterator from elements of an iterable for which a function returns True.

Example: Get only the even numbers from a list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using a lambda with filter
# The lambda checks if a number modulo 2 is 0 (i.e., it's even)
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4, 6, 8, 10]

C. sorted(iterable, key=function)

The sorted() function returns a new sorted list from the items in an iterable. The key argument specifies a function to be called on each element prior to making comparisons.

Example: Sort a list of dictionaries based on a specific value.

students = [
    {'name': 'Alice', 'score': 88},
    {'name': 'Bob', 'score': 95},
    {'name': 'Charlie', 'score': 76}
]
# Sort by the 'score' value in each dictionary
# The lambda tells sorted: "For each student 's', use s['score'] as the key for sorting."
sorted_students = sorted(students, key=lambda s: s['score'])
print(sorted_students)
# Output:
# [{'name': 'Charlie', 'score': 76}, {'name': 'Alice', 'score': 88}, {'name': 'Bob', 'score': 95}]

Another Example: Sort a list of words by their length.

words = ["apple", "banana", "kiwi", "strawberry", "fig"]
# Sort by the length of each word
sorted_by_length = sorted(words, key=lambda word: len(word))
print(sorted_by_length)
# Output: ['fig', 'kiwi', 'apple', 'banana', 'strawberry']

Advanced: Lambda with List Comprehensions

While map and filter are classic use cases, modern Python often favors list comprehensions for their readability. However, you can use lambdas within list comprehensions, especially when the logic is complex.

Example: Using map and a list comprehension for the same task.

numbers = [1, 2, 3, 4, 5]
# Using map and a lambda
squared_map = list(map(lambda x: x**2, numbers))
# Using a list comprehension (often preferred for simplicity)
squared_comprehension = [x**2 for x in numbers]
print(squared_map)       # Output: [1, 4, 9, 16, 25]
print(squared_comprehension) # Output: [1, 4, 9, 16, 25]

When might you use a lambda in a comprehension? When the transformation logic itself needs to be generated dynamically. This is a more advanced pattern.

# Let's say we have a list of functions and we want to apply each one to a number
functions = [lambda x: x+10, lambda x: x*2, lambda x: x**2]
number = 5
# We use a list comprehension to apply each lambda function
results = [f(number) for f in functions]
print(results)
# Output: [15, 10, 25]

When to Use (and Not Use) Lambda

✅ Good Use Cases for Lambda:

  1. Short, simple operations: When a function is one line and won't be reused.
  2. Functional programming: As an argument for map, filter, sorted, reduce, etc.
  3. GUI programming: For callbacks (e.g., button_command=lambda: print("Clicked")).

❌ Avoid Using Lambda When:

  1. The logic is complex: If the function needs more than one expression, use a def. Lambdas are not for readability if they become long and convoluted.
  2. The function is reused: If you need to call the same logic in multiple places, give it a name with def. It's easier to debug and understand.
  3. For simple if-else in a comprehension: A list comprehension with an if statement is almost always clearer than using filter with a lambda.

Bad Example (Hard to Read):

# Hard to read
filtered = list(filter(lambda x: x > 0 and x < 10, range(15)))

Good Example (Clearer):

# Much clearer
filtered = [x for x in range(15) if 0 < x < 10]

Summary Table

Concept Description Example
Lambda Definition An anonymous, one-line function. lambda x, y: x + y
map() Applies a function to all items in a list. list(map(lambda x: x*2, [1, 2, 3])) -> [2, 4, 6]
filter() Filters items from a list based on a condition. list(filter(lambda x: x > 5, [1, 6, 3, 8])) -> [6, 8]
sorted() Sorts a list, using a lambda to define the sort key. sorted([(1, 2), (3, 1)], key=lambda x: x[1]) -> [(3, 1), (1, 2)]
List Comprehension A more "Pythonic" way to create lists, often replacing map and filter. [x*2 for x in [1, 2, 3]] -> [2, 4, 6]
分享:
扫描分享到社交APP
上一篇
下一篇