高阶函数就是函数接受的参数是另一个函数
-
Map
- Map是python 内置的高阶函数,其可以传入俩个参数,第一个参数是函数,第二个参数是一个Iterable例如list。
def aa(a): return a*a r=map(aa,[1,2,3,4])
- Map的返回值是一个Iterator需要使用list 或者for 输出所有元素。
print([a for a in map(lambda cc:cc+cc,[1,2,3,4])])
-
Reduce
-
主要是用于聚合操作
from functools import reduce DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def char2num(s): return DIGITS[s] def str2int(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s))
-
filter
- 和map 类似都是接收俩个参数一个是函数一个参数是序列,filter 是用于对序列的过滤,通过判断true 或者是false 来决定元素的去留。
def _odd_iter(): n = 1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x: x % n > 0 def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列 if __name__ == '__main__': print([a for a in d(9)]) print([a for a in map(lambda cc:cc+cc,[1,2,3,4])]) # print([a for a in reduce(lambda a,b:a*10+b,map(lambda cc:cc*2+cc,range(6)))]) for n in primes(): if n < 1000: print(n) else: break
-
sorted
- 是一个进行用来排序的函数
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))