关于函数
关于函数:
1. 创建一个函数
def f(): pass |
2. 调用函数
def f(): pass f() |
3. 函数的返回值
a. 没有设定返回值
b. 单个返回值
c. 多个返回值
|
4. 高阶函数
def f(num): return num**num def fun(a,b,func): return func(a)+func(b) res=fun(2,5,f) print(res) |
5. 关于递归
特性: a. 调用自身函数 b. 有结束条件 c. 能用递归解决的问题,都可以循环解决. d. 效率比循环低…不太建议使用 def fuc(n): """求n的阶乘""" if n==1: return 1 return n*fuc(n-1) print(fuc(20))
eg: 斐波那契数列
|
6. 内置函数
https://docs.python.org/3.5/library/functions.html
|
- filter
def f(v): if v !="a": return v ret=filter(f,"abdasdsf") print(tuple(ret)) |
- map()
def ff(v): return v+"map"
ret1 = map(ff,"abdasdsf") print(list(ret1)) # ['amap', 'bmap', 'dmap', 'amap', 'smap', 'dmap', 'smap', 'fmap'] |
- 对比map和filter
def f(v): if v !="a": return v ret=filter(f,"abdasdsf") print(tuple(ret)) # ('b', 'd', 's', 'd', 's', 'f')
def ff(v): return v+"map"
ret1 = map(ff,"abdasdsf") print(list(ret1)) # ['amap', 'bmap', 'dmap', 'amap', 'smap', 'dmap', 'smap', 'fmap'] |
def f(v): if v !="a": return v ret=map(f,"abdasdsf") print(tuple(ret)) # (None, 'b', 'd', None, 's', 'd', 's', 'f')
def ff(v): return v+"map"
ret1 = filter(ff,"abdasdsf") print(list(ret1)) # ['a', 'b', 'd', 'a', 's', 'd', 's', 'f'] |
- reduce
(⊙o⊙)…,reduce貌似只支持两个值得操作
from functools import reduce def f(a,b): return a*b print(reduce(f,range(1,10)))
```````````````````````````````````````````分割线`````````````````````````````````````` 在有三个参数的时候就会报错:
|
- lambda
In [55]: f=lambda a :a+1
In [56]: f Out[56]: <function __main__.<lambda>>
In [57]: f(2) Out[57]: 3
Eg:与reduce一起使用实现阶乘
|