002集filter()函数及lambda()函数应用实例—python基础入门实例

1.filter()函数的基本语法如下:

filter ( function , iterable )

其中,function是一个用于判断的函数,iterable是一个可迭代对象,可以是列表、元组、集合或字符串等。filter()会将iterable中的每个元素依次传给function进行判断,返回满足条件的元素组成的迭代器。 让我们来看一个简单的例子,使用filter()函数过滤出列表中的偶数:

python 复制代码
# 定义一个函数,判断是否为偶数
def is_even(num):
    return num % 2 == 0  # 待筛选的列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # 使用filter函数过滤出偶数
filtered_numbers = filter(is_even, numbers)  # 将filter的结果转换为列表
result = list(filtered_numbers)
print(result)  # 输出: [2,4,6,8,10]

运行结果为:

F:\software\pythonProject\venv\Scripts\python.exe F:\software\pythonProject\0104.py

2, 4, 6, 8, 10

2. 使用Lambda()匿名函数,表达式进一步简化代码

lambda()匿名函数的主要用途是作为其他函数的参数,例如map()filter()reduce()等高阶函数。使用匿名函数可以避免编写额外的函数定义,使代码更加简洁明了。

有时候,我们只需要使用一次性的简单函数进行筛选,此时可以使用Lambda表达式,从而省略单独定义函数的步骤,使代码更加简洁。以上面的例子为例,我们可以改写为:

python 复制代码
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # 使用Lambda表达式过滤出偶数
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)  # 将filter的结果转换为列表
result = list(filtered_numbers)
# print(result)# 输出: [2, 4, 6, 8, 10]
print(result)  # 输出: [2,4,6,8,10]

运行结果如下:

以下为lambda()函数,fileter()函数实例:

python 复制代码
data1 = [66, 15, 91, 28, 98, 50, 7, 80, 99]  # data1为列表形式数据
myfilter = filter(lambda x: (x > 50), data1)  # filter()函数为过滤函数 lambda
data2 = list(myfilter)
print('data2是:', data2)
mapped = map(lambda x: (x * 2), data2)
data3 = list(mapped)
print('data3是:', data3)
mapped1 = filter(lambda x: (x > 150), data3)
data4 = list(mapped1)
print('data4是:', data4)
mapped2 = map(lambda x: (x > 150), data4)
data5 = list(mapped2)
print('data5是:', data5)

运行结果如下:

F:\software\pythonProject\venv\Scripts\python.exe F:\software\pythonProject\0104.py

data2是: [66, 91, 98, 80, 99]

data3是: [132, 182, 196, 160, 198]

data4是: [182, 196, 160, 198]

data5是: [True, True, True, True]

进程已结束,退出代码为 0

相关推荐
曲幽5 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805110 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon11 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly11 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程11 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly13 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风20 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风20 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python