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基于TCP实现会聊天的小机器人功能示例
2022-11-08 13:03:33
在Python程序中进行文件读取和写入操作的教程
2023-05-22 10:31:56
python和php哪个更适合写爬虫
2023-10-28 00:51:14
Python自动打印被调用函数变量名及对应值
2022-08-05 09:50:38
python中字符串变二维数组的实例讲解
2021-08-03 04:37:56
innerHTML 的些摘记
2009-06-01 15:42:00
Python 实现图像合成微缩效果
2023-08-19 22:15:16
Python实现自动清理电脑垃圾文件详解
2023-05-18 00:50:22
python小白切忌乱用表达式
2021-08-11 19:57:11
用 SQL 脚本将 Access 导入 MSSQL 2000/2005 方法
2008-10-22 13:51:00
python类属性学习深入讲解
2021-03-25 06:05:34
Mootools常用方法扩展(四)
2009-02-21 11:12:00
python 字典常用方法超详细梳理总结
2023-06-29 05:48:40
Python hashlib常见摘要算法详解
2023-07-29 20:04:09
ASP+AJAX做类似google的搜索提示
2008-10-24 13:49:00
解决python中os.system调用exe文件的问题
2023-11-29 14:46:13
Python使用Selenium爬取淘宝异步加载的数据方法
2021-05-17 05:31:57
Python实现网络自动化eNSP
2021-01-18 00:48:04
给网站界面预留退路
2009-03-25 20:32:00
Docker构建python Flask+ nginx+uwsgi容器
2023-07-25 06:36:43