高階函數、返回函數、閉包、匿名函數、裝飾器、偏函數
阿新 • • 發佈:2017-12-31
高階函數整理多個網友知識:
一、高階函數(函數作為變量,傳給另外一個函數使用)
高階函數例子: 備註:math模塊sqrt()函數求平方根。 #!/usr/bin/env python #-*- coding:utf-8 -*- import math def add(x, y, f): return f(x) + f(y) print add(100, 16, math.sqrt) [root@agile ~]# python test1.py 14.0 內置高階函數: (1)map函數:(第一個參數是函數,第二個參數是list,函數可以作用list中的每一個元素,並返回一個新的list,原list沒有改變) 備註:列表中每個值依次作為函數的參數,然後x1=s[0]表示第一個字母,x2=s[1:]表示第二個到最後一個字母。x1.upper()表示改成成大寫,x2.lower()表示成小寫。 #!/usr/bin/env python #-*- coding:utf-8 -*- def format_name(s): x1=s[0] x2=s[1:] return x1.upper()+x2.lower() print map(format_name, ['adam', 'LISA', 'barT']) [root@agile ~]# python test2.py ['Adam', 'Lisa', 'Bart'] (2)reducce函數(至少接受2個參數,第一個是函數,第二個是list,第三個是初始值,可省略。reduce是先拿list的前2個元素做計算,得到的結果再和第3個計算,結果再和第4個……這樣反復計算。如果有初始值,則初始值先和第一個計算,結果再和第2個計算……) #!/usr/bin/env python #-*- coding:utf-8 -*- def prod(x, y): return x*y print reduce(prod, [2, 4, 5, 7, 12]) [root@agile ~]# python test3.py 3360 (3)filter函數(過濾不滿足條件的元素,返回符合條件的元素list) 備註:依次傳1-101個數字進行求根,如果能求的filter函數就會返回。 #!/usr/bin/env python #-*- coding:utf-8 -*- import math def is_sqr(x): r=int(math.sqrt(x)) return r*r==x print filter(is_sqr, range(1, 101)) [root@agile ~]# python test4.py [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 例如,要從一個list [1, 4, 6, 7, 9, 12, 17]中刪除偶數,保留奇數,首先,要編寫一個判斷奇數的函數: def is_odd(x): return x % 2 == 1 然後,利用filter()過濾掉偶數: filter(is_odd, [1, 4, 6, 7, 9, 12, 17]) 結果:[1, 7, 9, 17] 利用filter(),可以完成很多有用的功能,例如,刪除 None 或者空字符串: def is_not_empty(s): return s and len(s.strip()) > 0 filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']) 結果:['test', 'str', 'END'] 註意: s.strip(rm) 刪除 s 字符串中開頭、結尾處的 rm 序列的字符。 當rm為空時,默認刪除空白符(包括'\n', '\r', '\t', ' '),如下: a = ' 123' a.strip() 結果: '123' a='\t\t123\r\n' a.strip() 結果:'123' (4)sorted排序函數(默認升序) #!/usr/bin/env python #-*- coding:utf-8 -*- def cmp_ignore_case(s1, s2): if s1.lower()<s2.lower(): return -1 if s1.lower()>s2.lower(): return 1 return 0 print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case) Python內置的 sorted()函數可對list進行排序: >>>sorted([36, 5, 12, 9, 21]) [5, 9, 12, 21, 36] 但 sorted()也是一個高階函數,它可以接收一個比較函數來實現自定義排序,比較函數的定義是,傳入兩個待比較的元素 x, y,如果 x 應該排在 y 的前面,返回 -1,如果 x 應該排在 y 的後面,返回 1。如果 x 和 y 相等,返回 0。 因此,如果我們要實現倒序排序,只需要編寫一個reversed_cmp函數: def reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 return 0 這樣,調用 sorted() 並傳入 reversed_cmp 就可以實現倒序排序: >>> sorted([36, 5, 12, 9, 21], reversed_cmp) [36, 21, 12, 9, 5] sorted()也可以對字符串進行排序,字符串默認按照ASCII大小來比較: >>> sorted(['bob', 'about', 'Zoo', 'Credit']) ['Credit', 'Zoo', 'about', 'bob'] 'Zoo'排在'about'之前是因為'Z'的ASCII碼比'a'小。
二、返回函數
三、閉包
四、匿名函數
五、裝飾器
六、偏函數
高階函數、返回函數、閉包、匿名函數、裝飾器、偏函數