Python學習之函數式編程

來源:互聯網
上載者:User

標籤:

本文和大家分享的主要是 python開發中函數式編程相關內容,一起來看看吧,希望對大家學習和使用這部分內容有所協助。 1. python把函數作為參數 import math def  add(x, y, f): return f(x) + f(y) print add(-5, 9, abs) print abs(-5) + abs(9) print add(25, 9, math.sqrt) 2. python中map()函數map() 是  Python  內建的高階函數,它接收一個函數  f  和一個  list ,並通過把函數  f  依次作用在 list  的每個元素上,得到一個新的  list  並返回。 def  format_name(s): return s[0].upper() + s[1:].lower() print map(format_name, [’adam’, ’LISA’, ’barT’]) 3.python中reduce()函數reduce() 函數也是 Python 內建的一個高階函數。 reduce() 函數接收的參數和  map() 類似,一個函數 f ,一個 list ,但行為和  map() 不同, reduce() 傳入的函數  f  必須接收兩個參數, reduce() 對 list 的每個元素反覆調用函數 f ,並返回最終結果值。 def  f(x, y): return x + y print reduce(f, [1, 3, 5, 7, 9]) # 25 def  prod(x, y): return x * y print reduce(prod, [2, 4, 5, 7, 12]) # 3360 4.python中filter()函數filter() 函數是  Python  內建的另一個有用的高階函數, filter() 函數接收一個函數  f  和一個 list ,這個函數  f  的作用是對每個元素進行判斷,返回  True 或  False , filter() 根據判斷結果自動過濾掉不合格元素,返回由符合條件元素組成的新 list 。 def  is_odd(x): return x % 2 == 1 print filter(is_odd, [1, 4, 6, 7, 9, 12, 17]) # [1, 7, 9, 17] def  is_not_empty(s): return s  and len(s.strip()) > 0 print filter(is_not_empty, [’test’,  None, ’’, ’str’, ’ ’, ’END’]) # [’test’, ’str’, ’END’] import math def  is_sqr(x):r = int(math.sqrt(x)) return r*r==x print filter(is_sqr, range(1, 101)) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 5.python中自訂排序函數sorted() 是一個高階函數,它可以接收一個比較函數來實現自訂排序,比較函數的定義是,傳入兩個待比較的元素  x, y ,如果  x 應該排在  y  的前面,返回  -1 ,如果  x  應該排在  y  的後面,返回  1 。如果 x  和  y  相等,返回  0 。 print sorted([36, 5, 12, 9, 21]) # [5, 9, 12, 21, 36] def  reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 return 0 print sorted([36, 5, 12, 9, 21], reversed_cmp) # [36, 21, 12, 9, 5] print sorted([’bob’, ’about’, ’Zoo’, ’Credit’]) # [’Credit’, ’Zoo’, ’about’, ’bob’] 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) # [’about’, ’bob’, ’Credit’, ’Zoo’] 6.python中返回函數Python 的函數不但可以返回 int 、 str 、 list 、 dict 等資料類型,還可以返回函數! def  calc_sum(lst): def  lazy_sum(): return sum(lst) return lazy_sum print f # print f() # 10 def  calc_prod(lst): def  lazy_prod(): def  f(x, y): return x * y return reduce(f, lst, 1) return lazy_prodf = calc_prod([1, 2, 3, 4]) print f() # 24 7.python中閉包 def  count():fs = [] for i  in range(1, 4): def  f(): return i*ifs.append(f) return fsf1, f2, f3= count() print f1() # 9 print f2() # 9 print f3() # 9 def  count():fs = [] for i  in range(1, 4): def  f(j): def  g(): return j*j return gr = f(i)fs.append(r) return fsf1, f2, f3 = count() print f1(), f2(), f3() # 1 4 9 8.python中匿名函數高階函數可以接收函數做參數,有些時候,我們不需要顯式地定義函數,直接傳入匿名函數更方便。 print map( lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # [1, 4, 9, 16, 25, 36, 49, 64, 81] print sorted([1, 3, 9, 5, 0],  lambda x,y: -cmp(x,y)) # [9, 5, 3, 1, 0]myabs =  lambda x: -x  if x < 0  else x  print myabs(-1) # 1 print myabs(1) # 1 print filter( lambda s: s  and len(s.strip())>0, [’test’,  None, ’’, ’str’, ’ ’, ’END’]) # [’test’, ’str’, ’END’] 9. python中decorator裝飾器什麼是裝飾器?·  問題:·  定義一個函數·  想在運行時動態增加功能·  又不想改動函數本身的代碼裝飾器的作用·  可以極大地簡化代碼,避免每個函數編寫重複性代碼·  列印日誌: @log·  檢測效能: @performance·  資料庫事務: @transaction· URL 路由: @post(’/register’) 9-1. python中編寫無參數decoratorPython 的  decorator  本質上就是一個高階函數,它接收一個函數作為參數,然後,返回一個新函數。 def  log(f): def  fn(x): print ’call ’ + f.__name__ + ’()...’ # call factorial()... return f(x) return fn@log def  factorial(n): return reduce( lambda x,y: x*y, range(1, n+1)) print factorial(10) # 3628800 print ’\n’ import time def  performance(f): def  fn(*args, **kw):t1 = time.time()r = f(*args, **kw)t2 = time.time() print ’call %s() in %fs’ % (f.__name__, (t2 - t1)) # call factorial() in 0.001343s return r return fn@performance def  factorial(n): return reduce( lambda x,y: x*y, range(1, n+1)) print factorial(10) # 3628800 9-2. python中編寫帶參數decorator import time def  performance(unit): def  perf_decorator(f): def  wrapper(*args, **kw):t1 = time.time()r = f(*args, **kw)t2 = time.time()t = (t2 - t1) * 1000  if unit==’ms’  else (t2 - t1) print ’call %s() in %f %s’ % (f.__name__, t, unit) # call factorial() in 1.250982 ms return r return wrapper return perf_decorator@performance(’ms’) def  factorial(n): return reduce( lambda x,y: x*y, range(1, n+1)) print factorial(10) # 3628800 9-3. python中完善decorator@decorator 可以動態實現函數功能的增加,但是,經過@decorator“ 改造 ” 後的函數,和原函數相比,除了功能多一點外,有沒有其它不同的地方? def  f1(x): passprint f1.__name__ # f1 def  log(f): def  wrapper(*args, **kw): print ’call...’ return f(*args, **kw) return [email protected] def  f2(x): passprint f2.__name__ # wrapper import time, functools def  performance(unit): def  perf_decorator(f): @functools.wraps(f) def  wrapper(*args, **kw):t1 = time.time()r = f(*args, **kw)t2 = time.time()t = (t2 - t1) * 1000  if unit==’ms’  else (t2 - t1) print ’call %s() in %f %s’ % (f.__name__, t, unit) return r return wrapper return perf_decorator@performance(’ms’) def  factorial(n): return reduce( lambda x,y: x*y, range(1, n+1)) print factorial.__name__ # factorial 10. python中偏函數當一個函數有很多參數時,調用者就需要提供多個參數。如果減少參數個數,就可以簡化調用者的負擔。 import functoolssorted_ignore_case = functools.partial(sorted, cmp=lambda s1, s2: cmp(s1.upper(), s2.upper()))print sorted_ignore_case([’bob’, ’about’, ’Zoo’, ’Credit’]) # [’about’, ’bob’, ’Credit’, ’Zoo’]來源: 部落格園

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.