# Python高阶函数_map/reduce/filter函数

### map/reduce

Python内建了map()reduce()函数。

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()传入的第一个蚕食是f，即函数对象本身。

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


>>>map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])
['1', '2', '3', '4', '5', '6', '7', '8', '9']


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))


### filter

Python内建的filter()函数用于过滤序列。

map()类似，filter()也接收一个函数和一个序列。和map()不同的是，filter()把传入的函数依次作用与每个元素，然后根据返回值是True还是False决定保留还是丢弃该元素。

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

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


def not_empty(s):
return s and s.strip()

filter(not_empty, ['A', '', 'B', None, 'C', '  '])
# 结果: ['A', 'B', 'C']


posted @ 2018-01-22 22:33  小破孩92  阅读(356)  评论(0编辑  收藏  举报