python把函数作为参数
1 | def add(x, y, f): |
常用函数
map()函数
1
2
3
4def f(x):
return x*x
print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
# 输出 [1, 4, 9, 10, 25, 36, 49, 64, 81]reduce()函数
1
2
3def f(x, y):
return x + y
print reduce(f, [1, 3, 5, 7, 9])filter()函数
1
2
3
4def is_odd(x):
return x % 2 == 1
filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
# 输出 [1, 7, 9, 17]sorted()函数
1
2
3
4
5
6
7
8
9
10sorted([36, 5, 12, 9, 21]) # 排序
def reversed_cmp(x, y):
if x > y:
return -1
if x < y:
return 1
return 0
sorted([36, 5, 12, 9, 21], reversed_cmp)
# 输出 [36, 21, 12, 9, 5]装饰者模式
1
2
3
4
5
6
7
8
9
10
11from functools import reduce
def log(f):
def fn(x):
print('call ' + f.__name__ + '()...')
return f(x)
return fn
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print(factorial(10))偏函数
1
2
3import functools
int2 = functools.partial(int, base=2)
# int2就是一个偏函数