杰瑞科技汇

map和filter在Python中如何高效使用?

Of course! map() and filter() are two of Python's most useful built-in functions for working with iterables (like lists, tuples, etc.). They are fundamental tools in functional programming and allow you to write concise and expressive code.

map和filter在Python中如何高效使用?-图1
(图片来源网络,侵删)

Let's break them down one by one.


The map() Function

map() applies a given function to every item of an iterable (like a list) and returns a map object (which is an iterator).

Syntax

map(function, iterable)

How it Works

  1. It takes a function as the first argument.
  2. It takes one or more iterables as subsequent arguments.
  3. It applies the function to the first item of each iterable, then the second item, and so on.
  4. It returns a map object, which is an iterator. You need to convert it to a list (or another iterable) to see the results.

Example 1: Basic map() with a List

Let's say we want to square every number in a list.

The "Classic" Way (without map)

map和filter在Python中如何高效使用?-图2
(图片来源网络,侵删)
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
    squared_numbers.append(num ** 2)
print(squared_numbers)
# Output: [1, 4, 9, 16, 25]

The map() Way First, we define a function that squares a number.

def square(x):
    return x ** 2
numbers = [1, 2, 3, 4, 5]
# Use map to apply the square function to every item in the numbers list
map_result = map(square, numbers)
# map_result is a map object, so we convert it to a list to see the values
squared_numbers = list(map_result)
print(squared_numbers)
# Output: [1, 4, 9, 16, 25]

Example 2: Using a Lambda with map

Lambda functions (small, anonymous functions) are perfect for map() when you only need a simple operation for one time.

numbers = [1, 2, 3, 4, 5]
# Use a lambda function to square each number
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)
# Output: [1, 4, 9, 16, 25]

Example 3: map() with Multiple Iterables

You can also use map() with more than one iterable. The function must then take as many arguments as there are iterables. The function stops when the shortest iterable is exhausted.

# Add corresponding elements from two lists
list1 = [1, 2, 3]
list2 = [10, 20, 30]
# The lambda function takes two arguments, x and y
summed_lists = list(map(lambda x, y: x + y, list1, list2))
print(summed_lists)
# Output: [11, 22, 33]

The filter() Function

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

map和filter在Python中如何高效使用?-图3
(图片来源网络,侵删)

Syntax

filter(function, iterable)

How it Works

  1. It takes a function as the first argument. This function must return a boolean value (True or False).
  2. It takes an iterable as the second argument.
  3. It applies the function to each item of the iterable.
  4. It includes only the items for which the function returned True.
  5. Like map(), it returns a filter object (an iterator), which you need to convert to a list to see the results.

Example 1: Basic filter() with a List

Let's filter out all the even numbers from a list.

The "Classic" Way (without filter)

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

The filter() Way First, we define a function that checks if a number is even.

def is_even(x):
    return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use filter to keep only the items where is_even returns True
filter_result = filter(is_even, numbers)
# filter_result is a filter object, so we convert it to a list
even_numbers = list(filter_result)
print(even_numbers)
# Output: [2, 4, 6, 8, 10]

Example 2: Using a Lambda with filter

Again, a lambda is perfect for this simple, one-time check.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use a lambda function to check for even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
# Output: [2, 4, 6, 8, 10]

Example 3: Filtering with None

If you pass None as the function, filter() will use the identity function. This means it will keep only the elements that evaluate to True in a boolean context. This is a very common and Pythonic way to remove "falsy" values (None, False, 0, , [], ).

mixed_list = [0, 1, False, 2, "", 3, [], "hello", {}, 4.5]
# Filter out all falsy values
truthy_values = list(filter(None, mixed_list))
print(truthy_values)
# Output: [1, 2, 3, 'hello', 4.5]

Modern Python: List Comprehensions and Generator Expressions

While map() and filter() are powerful, modern Python often favors list comprehensions and generator expressions. They are generally considered more readable and "Pythonic" for simple transformations and filtering.

List Comprehensions (for map-like operations)

A list comprehension can do the job of map() in a single, readable line.

# Instead of this:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
# You can write this:
squared_comp = [x**2 for x in numbers]
print(squared_comp)
# Output: [1, 4, 9, 16, 25]

List Comprehensions with if (for filter-like operations)

A list comprehension can also combine filtering and transformation.

# Instead of this:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squared = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
# You can write this (which is often clearer):
even_squared_comp = [x**2 for x in numbers if x % 2 == 0]
print(even_squared_comp)
# Output: [4, 16, 36, 64, 100]

Summary: When to Use Which?

Tool Best For Readability Performance
map() Applying a function to every item in one or more iterables. Good for simple, single operations. Can become less readable with complex logic or multiple iterables. Can be slightly faster than a list comprehension for simple functions due to internal optimizations.
filter() Selecting items from an iterable based on a condition. Good for simple filtering. Similar to map().
List Comprehension Transforming and/or filtering a list. The most common and readable choice for these tasks in modern Python. Generally more readable and concise, especially for combined operations. Very fast and idiomatic. Often the preferred choice.
Generator Expression The same as a list comprehension, but it creates an item on-the-fly instead of building a full list in memory. This is more memory-efficient for large datasets. Looks like a list comprehension but with instead of []. Memory-efficient.

Final Recommendation:

  • For most common use cases, start with a list comprehension. It's what most Python developers will expect and find easiest to read.
  • Use map() and filter() when you are explicitly working in a functional style, or when you need to chain operations with other functions from the functools module.
  • Use generator expressions ((x for x in items)) when you are working with very large datasets and don't need to store all the results in memory at once.
分享:
扫描分享到社交APP
上一篇
下一篇