网络编程
位置:首页>> 网络编程>> Python编程>> Python中filter与lambda的结合使用详解

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

作者:肖哥shelwin  发布时间:2022-03-03 01:35:03 

标签:Python,filter,lambda

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]

来源:https://blog.csdn.net/zjuxsl/article/details/77104157

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com