【每天1分钟】PYTHON基础之函数(高阶函数)
1. 什么是高阶函数
高阶函数:一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归),满足其一则为高阶函数。
参数为函数
>>> def bar():
print('in the bar......')
>>> def foo(func):
func()
print('in the foo......')
>>> foo(bar)
in the bar......
in the foo......
>>>
返回值为函数
>>> def bar():
print('in the bar......')
>>> def foo(func):
print('in the foo......')
return func
>>> foo(bar)
in the foo......
<function bar at 0x000001E66B373840>
>>> res = foo(bar)
in the foo......
>>> res()
in the bar......
>>>
2. 高阶函数
2.1 map
>>> num = [1, 2, 3, 4, 5]
>>> def square(x):
return x ** 2
# 模拟 map 函数
>>> def map_test(func, iter):
num_1 = []
for i in iter:
ret = func(i)
num_1.append(ret)
return num_1.__iter__()
# map_test函数
>>> print(list(map_test(square, num)))
[1, 4, 9, 16, 25]
>>>
# map函数
>>> print(list(map(square, num)))
[1, 4, 9, 16, 25]
# #当然map函数的参数1也可以是匿名函数、参数2也可以是字符串
>>> print(list(map_test(lambda x:x.upper(),"amanda")))
['A', 'M', 'A', 'N', 'D', 'A']
>>> print(list(map(lambda x:x.upper(),"amanda")))
['A', 'M', 'A', 'N', 'D', 'A']
>>>
2.2 filter
>>> names=["Alex","amanda","xiaowu"]
>>> #filter函数机制
>>> def filter_test(func,iter):
names_1=[]
for i in iter:
if func(i): #传入的func函数其结果必须为bool值,才有意义
names_1.append(i)
return names_1
>>> #filter_test函数
>>> print(filter_test(lambda x:x.islower(),names))
['amanda', 'xiaowu']
>>> #filter函数
>>> print(list(filter(lambda x:x.islower(),names)))
['amanda', 'xiaowu']
>>>
2.3 reduce
>>> #reduce函数不是内置函数,而是在模块functools中的函数,故需要导入
>>> from functools import reduce
>>> nums=[1,2,3,4,5,6]
>>> #reduce函数的机制
>>> def reduce_test(func,array,ini=None): #ini作为基数
if ini == None:
ret =array.pop(0)
else:
ret=ini
for i in array:
ret=func(ret,i)
return ret
>>> #reduce_test函数,叠乘
>>> print(reduce_test(lambda x,y:x*y,nums,100))
72000
>>> #reduce函数,叠乘
>>> print(reduce(lambda x,y:x*y,nums,100))
72000
>>> help(reduce)
Help on built-in function reduce in module _functools:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
>>>