filter()
函数是 Python 内置的函数之一,用于过滤序列中的元素,并返回满足指定条件的新序列。
filter()
函数的语法如下:
filter(function, iterable)
function
是一个函数,用于定义过滤的条件。可以是预定义函数、匿名函数或 lambda 表达式。iterable
是一个可迭代对象,例如列表、元组、字符串等。
filter()
函数遍历 iterable
中的每个元素,并将其传递给 function
进行判断。如果 function
返回值为 True
,则该元素会被保留在新的结果序列中;如果返回值为 False
,则该元素会被舍弃。
具体使用方式如下:
- 使用预定义函数:
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) # 输出结果: [2, 4, 6, 8, 10]
- 使用 lambda 表达式:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda num: num % 2 == 0, numbers))
print(even_numbers) # 输出结果: [2, 4, 6, 8, 10]
根据需求,可以将匹配条件从简单的字符串匹配改为更精确的正则表达式匹配,以避免匹配到不相关的字符串。