python高阶函数心得_python 高阶函数详解。

1,概念: Iterable 和 Iterator

Iterable 表示该变量可以被 for in 进行迭代。

Iterator 表示该变量可以被 next(o)进行迭代

(上一个表示有限迭代,下一个表示一个惰性的迭代概念,可以无限迭代。)

一般的Iterable 的变量有:

L=[{},[],(1,),{3:4},{3,4}]

for x in L:

print(isinstance(x,Iterable))

print(isinstance(x,Iterator))

true

false

可见,基础变量

List,tuple,set,dict 都是Iterable,但是 非Iterator.

Iterator 变量的产生方法有:

1,使用Iter(Iterable)的方式将Iterable->Iterator

2,使用生成器:

L=(x for x in L) 生成Iterator.

3,使用yield 将函数变成一个Iterator.

4, 使用map(f(x),Iterable)将其变为Iterator。

使用list(Iterator)可以将其变为列表。

高阶函数:

map:形式 map(f(x),Iterable) return a Iterator.f(x)需要返回值。

reduce:形式 reduce(f(x,y),Iterable. 进行不断的变量减少,返回所需值。

reduce 的函数需要在接收两个参数时能正确运行(即只允许两个位置参数)

filter:形式filter(f(x),Iterable)return a Iterator,f(x)返回true,false。

sorted(Iterable,key=func,reverse=false 返回Iterable.

对于Iterator ,其内部被转换为了list.

Iterator 生成器,是一个工具。其通过方法next(o)进行不断迭代产生数据。

也可以使用 for,list,....隐式调用next(o)来生成一个list...

函数的闭包:

def func()

def in_func()return xx return in_func 对于闭包函数首先: 1,[]类型变量直接全局有效。 2,对于int...非全局有效,需要加上nonlocal int ,不然会有一个分配错误。 使用闭包函数可以纪录该函数本身的信息,比如被调用次数。。等等。 此时,最好将该函数变更为一个对象。 例子:

def sumManager():

count=0

def thisCount():

nonlocal count

count=count+1

return count

def thissum(*L):

s=0

for x in L:

s=s+x

return s

return [thisCount,thissum]

sumCount,thissum=sumManager()

print(thissum(1,2,3),sumCount())

其中,1,使用nonlocal or []指定母函数中的变量可以被子函数访问。

2,两个函数需要同时返回,这样他们指向同一个函数体变量。

匿名函数:lambda x,y: 表达式,返回值就是表达式的值。

L=(lambda x,y:x+y)(3,4)

L=list(map(lambda x: x*x,[1,2,3]))

L=list(filter(lambda x:x%2==1,range(1,100)))

Decorator:装饰器,用于修饰函数。

1,func---本身是一个对象:所以具备对象属性:比如func.name

2,func---全参数调用:func(*args,kw)所有函数都可以支持这个参数表。

3,Decorator 的常见形式:

def log(f):

functools.wraps(f)

def wrapper(*args,*kw):

act1

t=f(args,kw)

act2

return t

return wrapper4,带参数类型: def log(para): def decorator(fun): functools.wraps(fun) def wrapper(*args,**kw): act1 t=fun(*args,**kw) act2 return t return wrapper return decorator def log(para):

if isinstance(para,str):

def decorator(f):@functools.wraps(f)br/>else:

@functools.wraps(para)
def wrapper(else:

@functools.wraps(para)kw):

print('begin')

sv=para(*k,**kw)

print('end')

return sv

return wrapper

else:

@functools.wraps(para)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值