python 高阶函数

映射类map():会根据提供的函数对指定序列做映射,映射的结果可以进行相应的类型转换。

语法格式如下:

# 第一个参数为映射函数,之后的一个或多个参数为可迭代类型,返回结果为map对象
map(func, *iterables) --> map object
# 迭代类型参数的个数,取决于映射函数所需的参数。

注意:当有多个迭代类型参数参加映射时,映射结果取决于长度小的迭代类型。即当其中一个迭代类型映射结束,则全部结束。

 

示例一:返回列表中元素平方后的结果

list_x = [1, 2, 3, 4, 5]
print(map(lambda x : x*x, list_x))
print(list(map(lambda x : x*x, list_x)))

-------------------------------------
<map object at 0x0000011C145567B8>
[1, 4, 9, 16, 25]

 

示例二:对两个列表中的元素对应求和

list_x = [1, 2, 3, 4, 5, 6]
list_y = [1, 2, 3, 4, 5]
print(list(map(lambda x,y : x+y, list_x, list_y)))

---------------------------
[2, 4, 6, 8, 10]

 

累积运算函数reduce():会根据提供的运算函数对迭代类型参数中的元素进行累积运算。

语法格式如下:

from functools import reduce
# 最后一个可选参数initial为累积运算的初始值
reduce(function, sequence[, initial]) -> value

 

示例三:对列表中的元素以10为初始值进行累乘

from functools import reduce
list_x = [1, 2, 3, 4, 5]
print(reduce(lambda x, y : x*y, list_x, 10))

---------------------------
1200

 

过滤类filter():根据提供的判断函数,对迭代类型参数进行过滤,保留使运算函数返回true的元素。

语法格式如下:

# 当第一个参数为None时,保留其中为true的元素
filter(function or None, iterable) --> filter object

 

示例四:保留列表中小于100的元素

list_x = [12, 809, 87, 900, 100]
print(filter(lambda x : True if x < 100 else False, list_x))
print(list(filter(lambda x : True if x < 100 else False, list_x)))

---------------------------
<filter object at 0x000002B8827267B8>
[12, 87]

 

总结一下

map()是映射类,reduce()是累积运算函数,filter()是过滤类,其中map()和reduce()返回的都为它们的对象,reduce()返回的是累积运算后的结果,使用reduce()时要from functools import reduce。

 

posted @ 2019-07-15 12:26  路漫漫我不畏  阅读(857)  评论(0编辑  收藏  举报