python(四)函数式编程


引入工具包下面要用

1
from functools import reduce

map

1
2
3
def f(x):
return x*x
print(list(map(f,[1,3,4,5])))

reduce(求和)

1
2
3
def myAdd(x,y):
return x+y
print(reduce(myAdd,[1,2,3,4]))

filter

1
2
3
def addFilter(x):
return x%2==1
print(list(filter(addFilter,[x for x in range(10)])))

sorted

1
2
3
4
5
print(sorted([36, 5, -12, 9, -21]))  #按照大小排序
print(sorted([36, 5, -12, 9, -21], key=abs)) #按照绝对值排序
print(sorted([36, 5, -12, 9, -21], key=abs,reverse=True)) #按照绝对值排序,反向
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower,reverse=True))

返回函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def lazy_sum(*argus):
ax=0
for a in argus:
ax+=a
return ax

def lazy_sum2(*argus):
def mySum():
ax=0
for a in argus:
ax+=a
return ax
return mySum

print(lazy_sum(1,2,3,4)) #立刻算出来

la = lazy_sum2(1,2,3,4) #当调用la()的时候才会算出来
print(la())

匿名函数

1
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))