当前位置:首页 » python教程 » 正文

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

看: 882次  时间:2020-12-30  分类 : 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中filter与lambda的结合使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!