python 高階函數詳解。

來源:互聯網
上載者:User

標籤:next   range   匿名函數   變數   基礎   列表   for   ext   tuple   

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 wrapper

    4,帶參數類型:    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):br/>@functools.wraps(f)
kw):
print(para)
print(‘begin‘)
sv=f(*k,*kw)
print(‘end‘)
return sv
return wrapper
return decoratorbr/>else:
@functools.wraps(para)
k,kw):
print(‘begin‘)
sv=para(*k,**kw)
print(‘end‘)
return sv
return wrapper

 也可以使用如下的辦法: def log(para): def decorator(func): def warpper(*args,**kw): sv=func(*args,**kw) return sv return warpper if isinstance(para,str): return decorator else: return decorator(para) ---------------------相當簡潔有效。 偏函數 import functools

>> int2 = functools.partial(int, base=2)

python 高階函數詳解。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.