# python 高阶函数

### 传入函数

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


map()函数这种能够接收函数作为参数的函数，称之为高阶函数（Higher-order function）。

L = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
L.append(f(n))
print L


reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)


>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25


>>> def fn(x, y):
...     return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579


>>> def fn(x, y):
...     return x * 10 + y
...
>>> def char2num(s):
...     return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579


def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
return reduce(fn, map(char2num, s))


def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

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


lambda函数的用法在下一节介绍。

### 排序算法

Python内置的sorted()函数就可以对list进行排序：

>>> sorted([36, 5, 12, 9, 21])
[5, 9, 12, 21, 36]


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]


>>> sorted(['about', 'bob', 'Zoo', 'Credit'])


def cmp_ignore_case(s1, s2):
u1 = s1.upper()
u2 = s2.upper()
if u1 < u2:
return -1
if u1 > u2:
return 1
return 0


>>> sorted(['about', 'bob', 'Zoo', 'Credit'], cmp_ignore_case)


### 函数作为返回值

def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax


def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum


>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function sum at 0x10452f668>


>>> f()
25


>>> f1 = lazy_sum(1, 3, 5, 7, 9)
>>> f2 = lazy_sum(1, 3, 5, 7, 9)
>>> f1==f2
False


f1()f2()的调用结果互不影响。

### 小结

Python提供的sum()函数可以接受一个list并求和，请编写一个prod()函数，可以接受一个list并利用reduce()求积。

posted @ 2014-09-28 00:59  wuhn  阅读(4282)  评论(0编辑  收藏