2024年3月20日发(作者:)

filter函数的用法wps

filter函数是一种Python内置函数,主要用于过滤序列,可以根据

自定义的条件过滤列表、元组、字典等序列对象中的元素。

filter函数的用法如下:

filter(function, iterable)。

其中,function为过滤函数,用于定义过滤条件;iterable为序列

对象,包含待过滤的元素。

filter函数返回一个过滤后的迭代器对象,其中包含符合条件的元

素。

下面是一个示例代码:

```。

#过滤出奇数。

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]。

odd_numbers = filter(lambda x: x % 2 == 1, numbers)。

print(list(odd_numbers))。

#过滤出长度大于等于3的字符串。

words = ['apple', 'banana', 'orange', 'pear', 'watermelon']。

long_words = filter(lambda x: len(x) >= 3, words)。

print(list(long_words))。

# 过滤出字典中value大于等于90的元素。

scores = {'Tom': 80, 'Jerry': 95, 'Lucy': 87, 'Emily': 92}。

high_scores = filter(lambda x: x[1] >= 90, ())。

print(dict(high_scores))。

```。

输出结果如下:

```。

[1,3,5,7,9]。

['apple', 'banana', 'orange', 'pear', 'watermelon']。

{'Jerry': 95, 'Emily': 92}。

```。

从示例中可以看出,filter函数可以根据不同的过滤条件对不同的

序列对象进行过滤,非常灵活实用。