Python基础(二)高阶函数map、reduce、filter

版权声明:转载请注明出处! https://blog.csdn.net/wfs1994/article/details/82120827

高阶函数:

  1. 函数的传入参数是一个函数名
  2. 函数的返回值是一个函数名
  3. 满足上述条件任意一个即为高阶函数

map:处理序列中的每一个元素,得到的结果是一个列表,该列表元素个数及位置与原来一样
reduce:处理一个序列,然后把序列进行合并操作
filter:遍历序列中的每一个元素,判断每个元素的到布尔值,如果是True则留下

map():
map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

举例说明,如果对一个列表[1, 2, 3, 4, 5]中的每一个元素做加1操作,就可以用map()来实现:

>>> l = [1, 2, 3, 4, 5]
>>> res = map(lambda x:x+1,l)
>>> print(list(res))
[2, 3, 4, 5, 6]

map()传入的第一个参数是lambda匿名函数。由于结果res是一个IteratorIterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list

#在不使用map()的情况下,可以通过如下代码实现每个元素加1的操作,相比之下map()仅需一行代码就能实现
list1 = [1,2,3,4,5]
def map_test(func,array):
    res = []
    for i in array:
        res.append(func(i))
    return res 
print(map_test(lambda x:x+1,list1)) 

将列表转换为字符串:

>>> list1 = [1,2,3,4,5]
>>> res = map(str,list1)
>>> print(list(res))
['1', '2', '3', '4', '5']

reduce():
reduce()把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

比方说对一个序列求和,就可以用reduce实现:

>>> from functools import reduce
>>> list3 = [1,2,3,4]
>>> res = reduce(lambda x,y:x+y,list3,)
>>> print(res)
10
>>> res1 = reduce(lambda x,y:x+y,list3,2)
>>> print(res1)
12
>>>

当然求和运算可以直接用Python内建函数sum(),没必要动用reduce(),但是如果要把序列[1,2,3,4]变换成整数1234,reduce就可以派上用场:

>>> res2 = reduce(lambda x,y:x*10+y,list3)
>>> print(res2)
1234

filter()
map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

list2 = ['test_1','test_2','3','test4']
res = filter(lambda x:not x.startswith('test'),list2)
print(list(res))

同样,在一个list中,删掉偶数,只保留奇数,可以这么写:

>>> list4 = [1,2,3,4,5]
>>> res = filter(lambda x:x%2==1,list4)
>>> print(list(res))
[1, 3, 5]
>>>

注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list

猜你喜欢

转载自blog.csdn.net/wfs1994/article/details/82120827