前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python内置函数(21)——filter

Python内置函数(21)——filter

作者头像
用户7798898
发布2020-09-27 15:32:31
2760
发布2020-09-27 15:32:31
举报

英文文档:

filter(function, iterable)

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.

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.

说明:

  1. filter函数用于过滤序列。过滤的方式则是采用传入的函数,去循环序列的元素调用,如果函数计算的结果为True则保留元素,否则将舍弃该元素。

代码语言:javascript
复制
>>> a = list(range(1,10)) #定义序列
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def if_odd(x): #定义奇数判断函数
    return x%2==1

>>> list(filter(if_odd,a)) #筛选序列中的奇数
[1, 3, 5, 7, 9]

  2. 当function参数传入None时,序列中的元素值如果为False,也会自动舍弃。

代码语言:javascript
复制
>>> c = ['',False,'I',{}] #定义序列
>>> c
['', False, 'I', {}]

>>> list(filter(None,c)) #筛选函数为None,自动舍弃序列中的False值,空字符串、False值、空序列都是False值,所以丢弃
['I']
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档