Python filter与lambda联合使用指南

云舒
云舒
发布时间:2026-10-13 | 4人浏览过
原创

本文详解Python内置函数filter与lambda表达式的结合用法。当第一个参数为None时,返回序列中所有真值元素;当提供函数时,仅保留使函数返回True的元素。通过具体代码示例展示了如何处理列表、元组及字符串,并解析了lambda语法中左侧单变量与右侧布尔表达式的约束。

filter函数基础定义

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时:


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(item)返回True的元素。此时,通常配合使用的lambda函数格式为:lambda x: expression(x)。

需要注意的是,lambda表达式冒号左侧只能有一个参数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 相关产品和应用

全部下载

专题列表