杰瑞科技汇

Python filter() 如何过滤掉 None 值?

Of course! In Python, "filtering out None" is a very common task. It means creating a new collection (like a list) that contains all the elements from the original collection, except for the None values.

Python filter() 如何过滤掉 None 值?-图1
(图片来源网络,侵删)

Here are the most common and effective ways to do this, from the most Pythonic to more explicit methods.

Method 1: Using a List Comprehension (Most Pythonic)

This is the most popular and readable way to filter None from a list in modern Python. It's concise, efficient, and easy to understand.

original_list = [1, None, 5, None, 8, 10, None, 3]
# Use a list comprehension to keep only items that are not None
filtered_list = [item for item in original_list if item is not None]
print(filtered_list)
# Output: [1, 5, 8, 10, 3]

How it works:

  • [item for item in original_list ... ]: This is the basic structure of a list comprehension. It iterates through original_list.
  • ... if item is not None: This is the filter condition. For each item, it checks if the condition is true. If it is, the item is included in the new list. If it's None, the condition is false, and it's skipped.

Note: You can also use if item != None. However, is not None is slightly more idiomatic and explicit for checking for the singleton None object.

Python filter() 如何过滤掉 None 值?-图2
(图片来源网络,侵删)

Method 2: Using the filter() Function

This is a classic functional programming approach. The built-in filter() function creates an iterator that yields items from an iterable for which a function returns True.

original_list = [1, None, 5, None, 8, 10, None, 3]
# filter() returns an iterator, so we convert it to a list
filtered_list = list(filter(lambda item: item is not None, original_list))
print(filtered_list)
# Output: [1, 5, 8, 10, 3]

How it works:

  • filter(function, iterable): It takes a function and an iterable.
  • lambda item: item is not None: This is a small, anonymous function. It takes one argument (item) and returns True if the item is not None, and False otherwise.
  • list(...): The filter() function returns an iterator, not a list. You must wrap it with list() to consume the iterator and create a new list.

Method 3: Using a Simple for Loop

This is the most explicit and traditional way. It's more verbose but can be easier for beginners to understand what's happening step-by-step.

original_list = [1, None, 5, None, 8, 10, None, 3]
filtered_list = []  # Start with an empty list
for item in original_list:
    if item is not None:
        filtered_list.append(item) # Add non-None items to the new list
print(filtered_list)
# Output: [1, 5, 8, 10, 3]

How it works:

Python filter() 如何过滤掉 None 值?-图3
(图片来源网络,侵删)
  1. Initialize an empty list, filtered_list.
  2. Loop through each item in the original_list.
  3. Check if the item is not None.
  4. If the condition is true, append the item to filtered_list.

Comparison and When to Use Each

Method Pros Cons Best For
List Comprehension Most Pythonic, concise, readable, and fast. Can become less readable if the condition is very complex. Most common cases. This is the default choice for filtering lists.
filter() function Functional style, good for simple transformations. Requires converting the result to a list (list(...)). Can be less readable than a comprehension for simple filters. When you're already using a functional style or when the filtering logic is a pre-existing function.
for Loop Very explicit, easy for beginners to understand, flexible for complex logic inside the loop. More verbose (more lines of code) than the other methods. Beginners, or when the filtering logic needs to be more complex than a simple if condition (e.g., multiple steps inside the loop).

Filtering None from Other Data Types

The same principles apply to other iterable collections like tuples and sets.

Filtering a Tuple

original_tuple = (1, None, "hello", None, 42)
filtered_tuple = tuple(item for item in original_tuple if item is not None)
print(filtered_tuple)
# Output: (1, 'hello', 42)

Filtering a Set

original_set = {1, None, 5, None, 8}
filtered_set = {item for item in original_set if item is not None} # Using a set comprehension
print(filtered_set)
# Output: {1, 8, 5}

Filtering None from a Dictionary

Filtering dictionaries is slightly different because you can filter based on either the keys or the values.

Filter out keys that are None

original_dict = {None: "value1", "key2": "value2", "key3": None}
filtered_dict = {key: value for key, value in original_dict.items() if key is not None}
print(filtered_dict)
# Output: {'key2': 'value2', 'key3': None}

Filter out values that are None

original_dict = {None: "value1", "key2": "value2", "key3": None}
filtered_dict = {key: value for key, value in original_dict.items() if value is not None}
print(filtered_dict)
# Output: {None: 'value1', 'key2': 'value2'}

Summary

For filtering None from a list, the list comprehension [item for item in my_list if item is not None] is the recommended, most Pythonic approach. It's clean, efficient, and clearly expresses your intent.

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