Python中的filter函数:过滤列表中的元素,并返回一个新的列表
发布时间:2023-05-27 07:00:27
Python中的filter函数是一个非常有用的函数,它可以用来过滤列表中的元素,并返回一个新的列表。
filter()函数的语法如下:
filter(function, iterable)
参数说明:
- function:用来筛选的函数。
- iterable:需要进行筛选的序列。
filter()函数的工作原理:将一个函数func作用于一个序列seq上,将每次func()返回值为True的元素放到一个新的序列中,最终返回这个新的序列。
filter()函数的返回值是一个迭代器对象,可以通过list()函数将其转换为列表对象。
下面通过几个例子来说明filter()函数的基本用法。
1. 过滤列表中偶数元素
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def even(x):
return x % 2 == 0
lst2 = filter(even, lst)
print(list(lst2)) # 输出结果:[2, 4, 6, 8, 10]
2. 过滤列表中所有的空字符
words = ['hello', '', 'world', 'python', '', '']
def not_empty(str):
return str and str.strip()
words2 = filter(not_empty, words)
print(list(words2)) # 输出结果:['hello', 'world', 'python']
3. 过滤列表中小于等于5的元素
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def less_than_5(x):
return x <= 5
lst2 = filter(less_than_5, lst)
print(list(lst2)) # 输出结果:[1, 2, 3, 4, 5]
从上面的例子中,我们可以看到filter()函数是非常灵活的,可以用来过滤任何类型的序列,并且可以使用不同的条件来过滤。
需要注意的是,在Python3中,filter()函数返回的是一个迭代器对象,如果需要将其转换为列表对象,需要使用list()函数进行转换,否则会产生TypeError异常。
总结:filter()函数是Python中一个非常有用的函数,可以用来对序列进行过滤,并返回一个新的序列对象。它可以使用不同的条件来过滤,非常灵活。在Python3中,需要使用list()函数将返回的迭代器对象转换为列表对象。
