廖雪峰Python 函数

廖雪峰Python 函数

函数

1
必选参数,默认参数,可变参数,关键字参数,命名关键字参数
1
函数名是一个变量指向函数,可以将另外的变量指向函数,函数也可以指向其它类型的值

高阶函数

1
函数名作为传入参数

map、reduce

1
2
3
4
5
6
7
8
map返回iterator、reduce函数 

>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
1
2
3
4
5
6
7
8
9
from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def char2num(s):
return DIGITS[s]

def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))

filter

1
2
3
4
5
6
7
8
和map差不多,传入函数作用于每一个元素,结果为True的保留

def is_odd(n):
return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]

sorted()

闭包 nonlocal

1
使用闭包时,对外层变量赋值前,需要先使用nonlocal声明该变量不是当前函数的局部变量。

匿名函数

1
lambda

装饰器

偏函数

递归

1
尾递归