python 高阶函数二 map()和reduce()

时间:2022-11-24 18:31:28

一、map()函数

map()函数接收两个参数,一个是函数,一个是Iterablemap将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回

 1 >>> from collections import Iterator
 2 >>> def f(x):
 3 ...     return x * x
 4 ... 
 5 >>> r = map(f, [1, 2, 3, 4, 5])
 6 >>> r
 7 <map object at 0x1013e5748>
 8 >>> isinstance(r, Iterator)
 9 True
10 >>> list(r)
11 [1, 4, 9, 16, 25]

二、reduce()函数

reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
1 >>> from functools import reduce
2 >>> def ad(x, y):
3 ...     return x + y
4 ... 
5 >>> reduce(ad, [1, 3, 5, 7, 9])
6 25
 1 >>> from functools import reduce
 2 >>> DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
 3 >>> def char2num(s):
 4 ...     return DIGITS[s]
 5 ... 
 6 >>> def str2int(s):
 7 ...     return reduce(lambda x, y: x * 10 + y, map(char2num, s))
 8 ... 
 9 >>> str2int('123456')
10 123456