map/reduce
t = list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) print(t) t = (x * x for x in range(10)) print(t) for value in t: print(value) from collections import Iterator t2 = isinstance(t, Iterator) print(t2)
reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
比方说对一个序列求和,就可以用reduce
实现:
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
当然求和运算可以直接用Python内建函数sum()
,没必要动用reduce
。
但是如果要把序列[1, 3, 5, 7, 9]
变换成整数13579
,reduce
就可以派上用场:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
from functools import reduce def fn(x,y): return x * 10 + y t = reduce(fn, [1,3, 5, 7, 9]) print(t) print(type(t)) 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)) t2 = str2int('12345') print(t2) print(type(t2)) from functools import reduce 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)) #label########## t = str2int('11112222') print(t)