python3基础之函数式编程

一、匿名函数

1.1 普通函数定义

In [57]:

def add(x,y):
    return x+y
print(add(1,2))
3

1.2 匿名函数定义: lambda 参数:结果

In [58]:

f = lambda x,y:x+y
print(f(1,2))
3

1.3 特点

In [59]:

#### 无函数名、无return

二、三元表达式

2.1 格式:条件为真时返回的结果 if 条件判断 else 条件为假返回的结果

In [60]:

x,y = 1,2
r = x if x >y else y
print (r)
2

三、map

适用场景:数据映射

In [61]:

list_x = [1,2,3]
def square(x):
    return x*x

In [62]:

r = map(square, list_x)
print(r)
print(list(r))
<map object at 0x04DF0570>
[1, 4, 9]

四、map与lambda

In [63]:

r = map(lambda x: x*x ,list_x)
print(list(r))
list_y = [1,2,3]
r = map(lambda x,y: x*x+y ,list_x ,list_y)
print(list(r))
[1, 4, 9]
[2, 6, 12]

五、reduce

reduce作为连续计算,一次的结果作为下一次的输入

In [64]:

from functools import reduce
r = reduce(lambda x,y :x+y ,list_x,10) # 10为初始值
print (r)
16

六、filter

In [65]:

list_x = [1,0,0,4]
r = filter(lambda x: True if x ==1 else False,list_x)
print(list(r))
[1]

lambda结合三元表达式,结合filter

七、装饰器

7.1 普通函数

In [66]:

import time
def f1():
    print("this is a function")
f1()
this is a function

需求变更,需要在打印功能前打印时间

In [67]:

def print_current_time(func):
    print(time.time())
    func()
print_current_time(f1)
1532500830.52
this is a function

In [68]:

### 缺点:没有和特定函数关联,完全依赖于调用

7.2 装饰器

In [69]:

def decorator(func):
    def wrapper():
        print(time.time())
        func()
    return wrapper

f = decorator(f1)
f()
1532500830.641
this is a function

7.3 装饰器:@语法糖

In [70]:

@decorator
def f1():
    print("this is a function")
f()
1532500830.69
this is a function

7.4 装饰器参数

In [71]:

def decorator2(func):
    def wrapper(*args,**kw):
        print(time.time())
        func(*args,**kw)
    return wrapper

In [72]:

@decorator2
def f2(name1,name2,**kw):
    print(kw)
    print(name1,name2)

f2("zhao","qian",a="sun",b="li")
1532500830.787
{'a': 'sun', 'b': 'li'}
zhao qian

八、git地址

https://coding.net/u/RuoYun/p/Python-Programming-Notes/git/tree/master/0.basics/10.functional_programming

おすすめ

転載: blog.csdn.net/u013584315/article/details/81203823