欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python中filter与lambda的结合使用详解

时间:2021-12-12 11:57:41|栏目:Python代码|点击:

filter是Python的内置方法。

官方定义是:

filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.

第一个参数为None的情形:

filter(None, '101') # '101'

filter(None, [True,False]) #[True]

filter(None, [True, 0, 1, -1]) #[True, 1, -1]

filter(None, (True, 1, 0, -1, False)) #(True, 1, -1)

第一个参数为function的情形,如果function(item)为True,则满足过滤条件。此时的lambda函数的形式是: lambda x: expression(x)。

注意到,:左边只能有一个元素x,:右边为一个关于x的表达式,且这个表达式的值要么是True, 要么是False.

filter(lambda x: x, [-1, 0, 1]) #[-1, 1]

filter(lambda x: not x, [-1, 0, 1]) #[0]

def f(x):
  return True if x == 1 else False
filter(lambda x: f(x), [-1, 0, 1]) #[1]

上一篇:python抢购软件/插件/脚本附完整源码

栏    目:Python代码

下一篇:你还在@微信官方?聊聊Python生成你想要的微信头像

本文标题:Python中filter与lambda的结合使用详解

本文地址:http://www.codeinn.net/misctech/186639.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有