本章主要涉及递归函数、lambda表达式、函数属性和注解、函数式编程工具(map/filter)
1.递归函数:简单循环和迭代
>>> def mysum(L):
... if not L:
... return 0
... else:
... return L[0] + mysum(L[1:])
...
>>> mysum([2,1,2,132,1])
138
>>>
>>> def mysum2(L):
... first,*rest = L
... return first if not rest else first + mysum2(rest)
...
>>> mysum2([1,2,3,4,5])
15
>>>
注:递归在内存空间和执行时间上效率较低
面对多层嵌套,递归逻辑更清晰
>>> def sumtree(L):
... tot = 0
... for x in L:
... if not isinstance(x,list):
... tot += x
... else:
... tot += sumtree(x)
... return tot
...
>>> L = [1,[2,3,4],2,[3,[4,5]]]
>>> sumtree(L)
24
>>>
lambda表达式
>>> def func(x,y,z):return x+y+z
...
>>> func(1,3,5)
9
>>> f = lambda x,y,z:x+y+z # 与上一句的函数等效
>>> f(1,2,3)
6
>>> d = f(1,2,3)
>>> d
6
>>> e = func(1,3,5)
>>> e
9
>>>
映射函数map
>>> li = [1,3,4]
>>> def func(x):return x**2 # 常规函数
...
>>> list(map(func,li))
[1, 9, 16]
>>> f = lambda x:x**3 # lambda表达式的函数也可以配合使用
>>> list(map(f,li))
[1, 27, 64]
>>>
>>> def myfunc(f,li): # 此函数模拟map实现过程,但map是内置函数,运行效率更高
... res = []
... for i in li:
... res.append(f(i))
... return res
...
>>> myfunc(func,li)
[1, 9, 16]
>>> myfunc(f,li)
[1, 27, 64]
>>>
>>> pow(3,3) # pow为内置函数
27
>>> list(map(pow,[1,2,3],[3,4,5])) # map搭配内置函数使用
[1, 16, 243]
>>>
>>> help(map)
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object # 详细了解map,此处可以看出,函数func需要传入几个参数,
| # 这里的 *iteralbes就传入几个
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
函数式编程工具filter
>>> range(-5,5)
range(-5, 5)
>>> list(range(-5,5))
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>> list(filter((lambda x:x>0),range(-5,5))) # 过滤掉不大于零的数,类似map,filter也是内置函数,运行效率很高
[1, 2, 3, 4]
>>>
>>> res = []
>>> for i in range(-5,5): # 使用for循环,实现filter同等的效果
... if i>0:
... res.append(i)
...
>>> res
[1, 2, 3, 4]
>>>
函数式编程工具reduce
>>> from functools import reduce # reduce不是内置函数
>>> reduce((lambda x,y:x+y),[1,2,3,4])
10
>>> num = 0
>>> for i in [1,2,3,4]: # 使用for循环,实现reduce同等的效果
... num += i
...
>>> num
10
>>>
>>> reduce((lambda x,y:x+y),[],10) # reduce可传入第三个参数,当序列为空时,作为默认值输出
10
>>>
总结map/filter/reduce
map: 映射函数,根据映射规则(即函数),输出序列的映射结果,序列长度与映射长度一致
filter: 过滤器,根据过滤规则(即函数),过滤序列的部分,输出满足过滤条件的值组成的序列,返回的序列小于等于传入的序列长度
reduce: 迭代运算,根据运算规则(即函数),对序列逐一进行操作,最后返回一个值,可以传入第三个参数(如果传入的序列为空,作为默认值输出)