map()
function
Receive two parameters, one is a function, and the other is Iterable
to map
apply the passed function to each element of the sequence in turn, and return the result as a new one Iterator
.
>>> 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]
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
The map() function can simplify programming
reduce() function
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> def char2num(s):
... digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
... return digits[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579
reduce() function
reduce (func, seq[, init()]) The
reduce() function is a repeated iteration function. Its execution process is: for each iteration, the previous iteration result and the next value in the sequence are used as the input of the function
init is optional. If specified, it is used as the first iteration. If not specified, the first element in seq is taken.
Use map
and reduce
write a str2float
function to '123.456'
convert a string to a floating point number 123.456
:
from functools import reduce
def str2float(s):
loc = s.find('.')
s1 = s.replace('.','')
num = reduce(fn, map(char2num, s1))
for n in range(len(s)-loc-1):
num = num/10.0
return num
def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
def fn(x, y):
return x * 10 + y
Reference source: https://www.liaoxuefeng.com/wiki/1016959663602400/1017329367486080