Pythonfilter函数的使用方法和案例
Python的filter()函数是一个内建函数,它用于对一个序列进行过滤操作,该函数接受两个参数, 个参数是函数,第二个参数是序列,它的返回值是一个新的序列,包含了函数返回True的元素。
使用方法
filter()函数的语法如下:
filter(function, iterable)
其中,function参数是一个函数,返回True或False。iterable参数是一个序列,包含需要过滤的元素。
示例
下面是一个示例,通过filter()函数过滤出一个列表中大于等于10的元素:
def greater_than_ten(x):
return x >= 10
numbers = [1, 5, 10, 15, 20]
result = filter(greater_than_ten, numbers)
print(list(result)) # [10, 15, 20]
上面的代码定义了一个函数greater_than_ten(),然后使用filter()函数过滤出大于等于10的元素。
也可以使用lambda表达式,将示例中的greater_than_ten()函数转换为一个匿名函数:
numbers = [1, 5, 10, 15, 20] result = filter(lambda x: x >= 10, numbers) print(list(result)) # [10, 15, 20]
示例中使用了lambda表达式,将greater_than_ten()函数转换为一个匿名函数。
filter()函数也可以过滤字符串中的元素,如下所示:
def is_vowel(letter):
vowels = "aeiou"
return letter in vowels
word = "hello"
result = filter(is_vowel, word)
print(list(result)) # ['e', 'o']
上面的代码定义了一个函数is_vowel(),然后使用filter()函数过滤出字符串中的元音字母。
也可以使用lambda表达式,将示例中的is_vowel()函数转换为一个匿名函数:
word = "hello" result = filter(lambda x: x in 'aeiou', word) print(list(result)) # ['e', 'o']
示例中使用了lambda表达式,将is_vowel()函数转换为一个匿名函数。
filter()函数还可以过滤出列表中的偶数,如下所示:
numbers = [1, 2, 3, 4, 5, 6] result = filter(lambda x: x % 2 == 0, numbers) print(list(result)) # [2, 4, 6]
上面的代码使用lambda表达式过滤出列表中的偶数。
filter()函数还可以过滤出字典中的元素,如下所示:
age = {"Tom": 28, "John": 30, "Mike": 25}
result = filter(lambda x: age[x] >= 28, age)
print(list(result)) # ['Tom', 'John']
上面的代码使用lambda表达式过滤出字典中值大于等于28的键。
总结
filter()函数用于对序列进行过滤操作,并返回满足条件的元素组成的新序列。它接受两个参数, 个参数是函数,第二个参数是序列。使用函数或lambda表达式定义过滤条件。
