杰瑞科技汇

Python filter如何高效筛选数字?

Of course! Filtering numbers in Python is a very common task. The best method to use depends on what you mean by "filter number."

Python filter如何高效筛选数字?-图1
(图片来源网络,侵删)

Let's break it down into the most common scenarios:

  1. Filtering a list to keep only the numbers.
  2. Filtering numbers based on a condition (e.g., greater than 10).
  3. Filtering non-numeric characters from a string.

Scenario 1: Filtering a List to Keep Only Numbers

You have a list with mixed data types (integers, floats, strings, etc.) and you want a new list containing only the numbers.

Method A: Using isinstance() with a List Comprehension (Recommended)

This is the most Pythonic and readable way. The isinstance() function checks if an object belongs to a specific type or a tuple of types. We'll check for both int and float.

mixed_list = [1, "hello", 3.14, "42", 7, "world", -5, 0.0]
# Use a list comprehension to filter for numbers (int and float)
numbers = [item for item in mixed_list if isinstance(item, (int, float))]
print(numbers)
# Output: [1, 3.14, 7, -5, 0.0]

Why use (int, float)? The second argument to isinstance() can be a single type or a tuple of types. This is a concise way to check for multiple types at once.

Python filter如何高效筛选数字?-图2
(图片来源网络,侵删)

Method B: Using a for Loop (More Verbose)

This achieves the same result as the list comprehension but is more explicit and can be easier for beginners to understand.

mixed_list = [1, "hello", 3.14, "42", 7, "world", -5, 0.0]
numbers = []
for item in mixed_list:
    if isinstance(item, (int, float)):
        numbers.append(item)
print(numbers)
# Output: [1, 3.14, 7, -5, 0.0]

Scenario 2: Filtering Numbers Based on a Condition

You have a list of numbers and you want to keep only those that meet a specific criterion (e.g., positive, even, greater than a certain value).

Method A: Using a List Comprehension (Recommended)

List comprehensions are perfect for this. The syntax is [expression for item in list if condition].

Example 1: Keep only even numbers

Python filter如何高效筛选数字?-图3
(图片来源网络,侵删)
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)
# Output: [2, 4, 6, 8, 10]

Example 2: Keep only numbers greater than 5

numbers = [1, 6, 2, 8, 3, 9, 4, 10]
greater_than_five = [num for num in numbers if num > 5]
print(greater_than_five)
# Output: [6, 8, 9, 10]

Method B: Using the filter() Function

The built-in filter() function is designed for this. It takes a function and an iterable, and returns an iterator containing only the items for which the function returns True.

You can use a lambda (an anonymous, one-line function) for the condition.

numbers = [1, 6, 2, 8, 3, 9, 4, 10]
# filter() returns an iterator, so we convert it to a list
greater_than_five = list(filter(lambda num: num > 5, numbers))
print(greater_than_five)
# Output: [6, 8, 9, 10]

Which is better? For simple conditions, list comprehensions are often considered more readable by Python developers. For more complex, reusable filtering logic, filter() with a named function can be cleaner.


Scenario 3: Filtering Non-Numeric Characters from a String

You have a string with letters, numbers, and symbols, and you want to extract only the digits.

Method A: Using a List Comprehension with str.isdigit()

This is a very common and elegant pattern. str.isdigit() returns True if all characters in the string are digits and there is at least one character.

my_string = "abc123def45!@#"
# Filter for characters that are digits
digits = [char for char in my_string if char.isdigit()]
# Join the list of characters back into a string
number_string = "".join(digits)
print(digits)          # Output: ['1', '2', '3', '4', '5']
print(number_string)   # Output: '12345'

Method B: Using a Regular Expression (Most Powerful)

For complex patterns (e.g., extracting floating-point numbers or negative numbers), regular expressions are the best tool.

import re
my_string = "Price: $19.99, Discount: 5.5%, Total: 14.49"
# Find all sequences of one or more digits, optionally followed by a decimal point and more digits.
# \d+ matches one or more digits.
# \.? matches an optional literal dot.
# \d* matches zero or more digits.
numbers = re.findall(r"\d+\.?\d*", my_string)
print(numbers)
# Output: ['19.99', '5.5', '14.49']

Summary Table

Goal Best Method Example Code
Keep only numbers from a mixed list List comprehension with isinstance() [x for x in my_list if isinstance(x, (int, float))]
Filter numbers by a simple condition List comprehension [x for x in my_numbers if x > 10]
Filter numbers by a simple condition filter() with lambda list(filter(lambda x: x > 10, my_numbers))
Extract digits from a string List comprehension with str.isdigit() [c for c in my_string if c.isdigit()]
Extract complex number patterns from a string Regular Expressions (re module) re.findall(r"pattern", my_string)
分享:
扫描分享到社交APP
上一篇
下一篇