首页 > Python函数 > 正文

python函数每日一讲 - filter函数过滤序列

描述

filter()函数用于过滤序列, 过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

filter()函数接收一个函数 func 和一个iterable(可以是list,字符串等),这个函数 func 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,最后将返回 True 的元素放到新列表中。


语法

filter(function, iterable)


参数

function -- 判断函数。

iterable -- 可迭代对象。


返回值

返回符合条件的新列表。


适用版本

2.x

3.x


英文解释

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.


Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.


实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [1,2,4,6,8,9]
def is_gt_5(num):
    return num > 5
new_list = filter(is_gt_5, list)
print(new_list)


输出结果

[6, 8, 9]


高级用法

1. 过滤非数字字符

>>> name = 'pythontab.com 2018'
>>> filter(str.isdigit, name)
'2018'

2. 过滤数字

>>> filter(str.isalpha, name)
'pythontabcom'

3. 保留数字和小数点

>>> filter(lambda char: char in ‘0123456789.’, name) 
'.2018'


上一篇:python函数每日一讲 - exec执行函数
下一篇:python函数每日一讲 - float函数类型转换详解

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):

群1: 87464755

群2: 333646237

群3: 318130924

群4: 385100854