python把函數作為參數


python把函數作為參數
import math
 
def add(x, y, f):
    return f(x) + f(y)
 
print add(25, 9,math.sqrt)
 
python中map()函數的應用。將首字母大寫,其他的小寫
def format_name(s):
    return s.capitalize()
    #return s[0].upper()+s[1:].lower()
print map(format_name,['admin','LiSa','kILL'])
 
python中reduce()函數的應用
reduce和map函數相似,但是他只能傳入兩個參數與map的多個有區別,他還有迭代的功能呢!
def muil(x,y):
    return x*y
print reduce(muil,[1,2,3,4])
 
filter()函數接收一個函數 f 和一個list,這個函數 f 的作用是對每個元素進行判斷,返回 True或 False,
filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。
def is_odd(x):
    return  x%2==1
filter(is_odd,[1,3,2,9])
利用filter除去None和空字符串
def is_not_empty(s):
    return s and len(s.strip())>0
filter(is_not_empty,['test',None,'    '])
 
 
Python內置的 sorted()函數可對list進行排序:【但是僅僅實行的順序排序,但是逆序卻是另一個函數】我們今天寫的就是另一種函數的功能。
對於比較函數cmp_ignore_case(s1, s2),要忽略大小寫比較,就是先把兩個字符串都變成大寫(或者都變成小寫),再比較。
參考代碼:
def cmp_ignore_case(s1, s2):
    u1 = s1.upper()
    u2 = s2.upper()
    if u1 < u2:
        return -1
    if u1 > u2:
        return 1
    return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
 
 
我們在sorted這個高階函數中傳入自定義排序函數就可以實現忽略大小寫排序。請用functools.partial把這個復雜調用變成一個簡單的函數:functools.partial是隱形的創建一個新函數。
要固定sorted()的cmp參數,需要傳入一個排序函數作為cmp的默認值。
參考代碼:
import functools
sorted_ignore_case = functools.partial(sorted, cmp=lambda s1, s2: cmp(s1.upper(), s2.upper()))
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM