python的map函数和reduce_python函数_map()、filter()和reduce()

本文介绍了Python中的函数式编程概念,重点讲解了纯函数的特点,并通过示例展示了如何使用map()、filter()和reduce()函数。map()函数用于对可迭代对象的每个元素应用指定函数,filter()函数则用于根据给定条件筛选可迭代对象的元素,而reduce()函数用于对序列进行累积操作。这些函数在不改变原始数据的基础上提供了强大的数据处理能力。
摘要由CSDN通过智能技术生成

1.所谓函数式编程,是指代码中每一块都是不可变的,都由纯函数的形式组成。这里的纯函数,是指函数本身相互独立、互不影响,对于相同的输入,总会有相同的输出。

例如:

defmultiply_2(list):for index inrange(0, len(list)):

list[index]*= 2

returnlist

listDemo= [1, 2, 3, 4, 5]print(multiply_2(listDemo))

运行结果:

[2, 4, 6, 8, 10]

multiply_2()函数并不是纯函数式代码,因为它改变了列表list中的值,所以多次调用都会有不同的结果。

再例如:

defmultiply_2_pure(list):

new_list=[]for item inlist:

new_list.append(item* 2)returnnew_list

listDemo= [1, 2, 3, 4, 5]#print(multiply_2(listDemo))

print(multiply_2_pure(listDemo))

运行结果:

[2, 4, 6, 8, 10]

这就是一个纯函数式代码因为在multiply_2_pure()中新建g了一个new_list列表,会将结果保存到新列表中并不会改变list的值。

2.map()函数

格式:map(function, iterable)

参数含义:其中,function 参数表示要传入一个函数,其可以是内置函数、自定义函数或者 lambda 匿名函数;iterable 表示一个或多个可迭代对象,可以是列表、字符串等。

例如:

listDemo = [1, 2, 3, 4, 5]

new_list= map(lambda x: x * 2, listDemo)print(list(new_list))

运行结果:

[2, 4, 6, 8, 10]

map() 函数可传入多个可迭代对象作为参数

listDemo1 = [1, 2, 3, 4, 5]

listDemo2= [3, 4, 5, 6, 7]

new_list= map(lambda x,y: x +y, listDemo1,listDemo2)print(list(new_list))

运行结果:

[4, 6, 8, 10, 12]

tips:该函数返回的是一个 map 对象,不能直接输出,可以通过 for 循环或者 list() 函数来显示。

2.filter()函数

格式:filter(function, iterable)

参数含义:funcition 参数表示要传入一个函数,iterable 表示一个可迭代对象。

filter() 函数的功能:是对 iterable 中的每个元素,都使用 function 函数判断,并返回 True 或者 False,最后将返回 True 的元素组成一个新的可遍历的集合。(条件过滤)

listDemo = [1, 2, 3, 4, 5]

new_list= filter(lambda x: x % 2 ==0, listDemo)print(list(new_list))

运行结果:

[2, 4]

3.reduce()函数

格式:reduce(function, iterable)

参数含义:function 规定必须是一个包含 2 个参数的函数;iterable 表示可迭代对象。

importfunctools

listDemo= [1, 2, 3, 4, 5]

product= functools.reduce(lambda x, y: x *y, listDemo)print(product)

运行结果:

120

tips: reduce() 函数在 Python 3.x 中已经被移除,放入了 functools 模块,因此在使用该函数之前,需先导入 functools 模块。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值