python函数_map()、filter()和reduce()

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

例如:

def multiply_2(list):
    for index in range(0, len(list)):
        list[index] *= 2
    return list
listDemo = [1, 2, 3, 4, 5]
print(multiply_2(listDemo))

运行结果:

[2, 4, 6, 8, 10]

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

再例如:

def multiply_2_pure(list):
    new_list = []
    for item in list:
        new_list.append(item * 2)
    return new_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 表示可迭代对象。

import functools
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 模块。

猜你喜欢

转载自www.cnblogs.com/lishanstudy/p/12820373.html
今日推荐