高阶函数
- 变量可指向函数
>>> abs # 函数
<built-in function abs>
>>> abs(-0) # 函数调用
0
>>> func = abs # 变量可指向函数
>>> func(-9) # 调用变量 = 调用函数
9
- 函数名 && 变量
>>> abs = 9 # 函数名可以作为变量使用
>>> abs(-9) # 函数名作为变量时,相当于重新赋值,失去之前的函数功能
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
- 高阶函数 —— 一个函数接受另一个函数作为参数
>>> def sum(x,y,f):
return f(x) + f(y)
调用高阶函数
>>> sum(3,-9,abs) # 12
映射
- map()
- 接收参数 :函数、Iterable
- 计算过程 :将传入函数依次作用于Iterable中的每个元素
- 返回结果 :Iterator(惰性序列)
>>> def f(x):
return x * x
>>> map(f,[0,1,2,3,4,5]) # 相当于[f(0),f(1),f(2),f(3),f(4),f(5)]
- 其效果为:
map(f,[0,1,2,3,4,5]) = [f(0),f(1),f(2),f(3),f(4),f(5)]
map(f,[0,1,2,3,4,5])函数对应的示意图:
>>> f = [0,2,4,6]
>>> f.map(w => w + 1)
[1,3,5,7]
- reduce()
- 接收参数 :函数、Iterable
- 计算过程 :函数作用在序列上,将结果与序列的下一个元素进行累计计算
- 返回结果 :累积计算结果
>>> def f(x,y):
return x * 10 + y
>>> reduce(f,[0,1,2,3,4,5]) # 相当于f(f(f(f(f(0,1),2),3),4),5)
- 其效果为:
reduce(f,[0,1,2,3,4,5]) = f(f(f(f(f(0,1),2),3),4),5)
reduce(f,[0,1,2,3,4,5])函数对应的示意图:
累加:
>>> f = [1,2,3,4,5,6,7,8,9]
>>> f.reduce(x, y => x + y)
45
- map() && reduce()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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]
print(reduce(fn, map(char2num, '13579'))) #13579
过滤算法
filter()
- 接收参数 :函数、序列
- 计算过程 :将传入函数依次作用于序列中的每个元素
- 返回结果 :Iterator,仅返回序列中符合条件的元素
利用filter求素数
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
for n in primes():
if n < 1000:
print(n)
else:
break
# 构造从3开始的奇数序列[生成器,无限序列]
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__':
main()
排序算法
sorted()
- 可对list进行排序
- 数字排序 :默认从小到大
- 字符串排序 :默认按照ASCII大小比较,‘Z’<‘a’。先大写后小写
>>> sorted([20,14,-22,4,9]) # 默认从小到大
[-22, 4, 9, 14, 20]
>>> sorted([20,14,-22,4,9],key=abs) # key处理后再排序
[4, 9, 14, 20, -22]
>>> sorted(['Bob','Jimmy','grace','amey','Zoo']) # 默认ASCII码从小到大排序
['Bob', 'Jimmy', 'Zoo', 'amey', 'grace']
>>> sorted(['Bob','Jimmy','grace','amey','Zoo'],key=str.lower) # 忽略大小写排序
['amey', 'Bob', 'grace', 'Jimmy', 'Zoo']
>>> sorted(['Bob','Jimmy','grace','amey','Zoo'],key=str.lower,reverse=True) # 反向排序
['Zoo', 'Jimmy', 'grace', 'Bob', 'amey']