杰瑞科技汇

Python filter与lambda如何协同使用?

Of course! Let's break down the filter() function and lambda expressions in Python. They are often used together, and understanding them separately first is key.

Python filter与lambda如何协同使用?-图1
(图片来源网络,侵删)

Part 1: The filter() Function

The filter() function is a built-in Python tool that constructs an iterator from elements of an iterable for which a function returns True.

Syntax

filter(function, iterable)

Parameters

  • function: A function that tests each element of the iterable. It must return a boolean value (True or False). If you pass None, all elements of the iterable that are false are removed.
  • iterable: Any iterable object (like a list, tuple, set, etc.).

Return Value

  • An iterator. This means it doesn't immediately create a new list. Instead, it generates items one by one as you loop over it or convert it to a list.

How it Works

  1. filter() takes each item from the iterable.
  2. It passes that item to the function.
  3. If the function returns True, the item is included in the result.
  4. If the function returns False, the item is discarded.

Example with a Regular Function

Let's say we want to filter a list of numbers to get only the even numbers.

def is_even(num):
    """Returns True if a number is even, False otherwise."""
    return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use filter to get only the even numbers
# filter() returns an iterator, so we convert it to a list to see the results
even_numbers_iterator = filter(is_even, numbers)
even_numbers_list = list(even_numbers_iterator)
print(even_numbers_list)
# Output: [2, 4, 6, 8, 10]

Part 2: The lambda Expression

A lambda is a small, anonymous function defined using the lambda keyword. It's a way to create a simple, one-line function without formally defining it using def.

Syntax

lambda arguments: expression

Parameters

  • arguments: A comma-separated list of input parameters (just like a regular function).
  • expression: A single expression that is evaluated and returned. The expression's result is the return value of the lambda function.

Key Characteristics

  • Anonymous: It has no name.
  • Single Expression: Can only contain a single expression. You cannot have statements, multiple lines, or complex logic like if/else (though you can use a ternary conditional expression).
  • Concise: Ideal for short, simple operations.

Example

Let's create a lambda function that adds 10 to a number.

Python filter与lambda如何协同使用?-图2
(图片来源网络,侵删)
# Regular function
def add_ten_regular(num):
    return num + 10
# Equivalent lambda function
add_ten_lambda = lambda num: num + 10
print(add_ten_regular(5))      # Output: 15
print(add_ten_lambda(5))       # Output: 15

Part 3: Combining filter() and lambda

This is where the real power and convenience come in. Often, the function you want to use with filter() is very simple and only needed for that one purpose. Writing a full def block is overkill. This is the perfect use case for lambda.

The Scenario

Let's go back to our first example: filtering a list of numbers to get only the even numbers. Instead of defining is_even, we can use a lambda directly inside filter().

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use a lambda as the function for filter
# The lambda checks if a number is even: (num % 2 == 0)
even_numbers = list(filter(lambda num: num % 2 == 0, numbers))
print(even_numbers)
# Output: [2, 4, 6, 8, 10]

How to read this: "Filter the numbers list, keeping only the elements for which the lambda function (lambda num: num % 2 == 0) returns True."

Another Example: Filtering by String Length

Let's say we have a list of words and we want to keep only those that have more than 4 characters.

Python filter与lambda如何协同使用?-图3
(图片来源网络,侵删)
words = ["apple", "kiwi", "banana", "pear", "strawberry", "fig"]
# Filter words with length > 4
long_words = list(filter(lambda word: len(word) > 4, words))
print(long_words)
# Output: ['apple', 'banana', 'strawberry']

Example with None as the function

If you pass None as the function, filter() will keep only the elements that evaluate to True in a boolean context. This effectively removes all "falsy" values (like 0, False, None, empty strings , and empty lists []).

mixed_data = [0, 1, "", "hello", False, True, [], [1, 2], None]
# Keep only the "truthy" elements
truthy_data = list(filter(None, mixed_data))
print(truthy_data)
# Output: [1, 'hello', True, [1, 2]]

Modern Python: List Comprehensions

While filter() with lambda is a classic and powerful combination, modern Python often favors list comprehensions (and generator expressions) for readability and conciseness.

A list comprehension can often do the same job as filter() and lambda in a single, readable line.

Let's compare the three approaches for our "even numbers" example.

filter() with a def function (More verbose)

def is_even(num):
    return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(is_even, numbers))
print(even_numbers)

filter() with a lambda (Classic approach)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda num: num % 2 == 0, numbers))
print(even_numbers)

List Comprehension (Modern, often preferred)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)

The list comprehension [num for num in numbers if num % 2 == 0] is very clear: "give me num for each num in numbers, but only if the condition is met."

Summary: When to Use What

Method Pros Cons Best For
filter() + lambda Functional style, concise for simple logic. Can be less readable than a list comprehension for beginners. Quick, simple filtering where you don't need to transform the item.
List Comprehension Highly readable, flexible (can filter and transform in one go), generally faster. Can become complex if the logic is very nested. Most common use case for creating new lists based on conditions.
filter() + def Very clear for complex logic that needs to be reused. More verbose for a simple, one-off check. When the filtering logic is complex and you want to give it a descriptive name for reusability.

Final Recommendation: For most everyday filtering tasks, list comprehensions are the idiomatic and often more readable choice in modern Python. However, understanding filter() and lambda is essential as you will encounter them frequently in existing code and in more functional programming paradigms.

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