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

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

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

标签:Python,filter,lambda
0
投稿

猜你喜欢

  • Python判断以什么结尾以什么开头的实例

    2021-07-31 06:42:58
  • 高效交换XML文档

    2008-01-03 14:16:00
  • 详解Python中命令行参数argparse的常用命令

    2022-06-06 15:59:30
  • .net连接Mysql封装类代码 可直接调用

    2024-01-14 15:16:16
  • Python可变参数会自动填充前面的默认同名参数实例

    2022-05-24 05:00:43
  • mysql之innodb的锁分类介绍

    2024-01-27 00:50:10
  • Python 面向对象静态方法、类方法、属性方法知识点小结

    2022-02-10 07:45:52
  • PHP中把stdClass Object转array的几个方法

    2023-11-19 06:56:33
  • 用Python的SimPy库简化复杂的编程模型的介绍

    2023-06-19 16:55:45
  • select * from sp_who的解决方案

    2024-01-15 09:55:52
  • javascript与jsp发送请求到servlet的几种方式实例

    2023-06-15 15:59:30
  • 让网站容易被发现

    2009-04-20 20:35:00
  • perl 简明教程 perl教程集合

    2023-08-08 19:58:12
  • 对python中assert、isinstance的用法详解

    2022-04-29 14:10:54
  • mysql 8.0.27 安装配置方法图文教程(Windows64位)

    2024-01-19 07:37:59
  • 解决win7操作系统Python3.7.1安装后启动提示缺少.dll文件问题

    2021-08-09 00:56:29
  • python计算n的阶乘的方法代码

    2023-08-20 07:33:00
  • pdo中使用参数化查询sql

    2023-07-20 21:11:21
  • 在Python中将函数作为另一个函数的参数传入并调用的方法

    2023-04-10 07:32:26
  • 详解python 支持向量机(SVM)算法

    2022-03-06 02:11:24
  • asp之家 网络编程 m.aspxhome.com