程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python 高階函數、高階內建函數及柯裡化 詳解

編輯:Python

Python 高階函數、高階內建函數及柯裡化

  • 1、高階函數
    • 1.1 Python 函數
    • 1.2 高階函數
    • 1.3 實現計數器的高階函數
    • 1.4 注意以下兩個函數的區別
      • 1.4.1 函數內嵌套函數
      • 1.4.2 函數內部返回全局函數
  • 2、內建高階函數
    • 2.1 排序 sorted
      • 2.1.1 語法
      • 2.1.2 示例
    • 2.2 過濾 filter
      • 2.2.1 語法
      • 2.2.2 示例
    • 2.3 映射 map
      • 2.3.1 語法
      • 2.3.2 示例
  • 3、柯裡化
    • 3.1 概念
    • 3.2 示例

1、高階函數

1.1 Python 函數

  • 函數在 Python 裡是一等公民(First-Class Object)
  • 函數也是對象,是可調用對象
  • 函數可以作為普通變量,也可以作為函數的參數、返回值

1.2 高階函數

在數學和計算機科學中,高階函數(High-order Function)應當至少滿足下面一個條件的函數:

  • 接受一個或多個函數作為參數
  • 輸出一個函數

1.3 實現計數器的高階函數

def counter(base):
def _counter(step=1):
nonlocal base
base += step
return base
return _counter
# 基數是0,步長為2的技術器
counter1 = counter(base=0)
for i in range(3):
print(counter1(step=2))
# Out
2
4
6

1.4 注意以下兩個函數的區別

1.4.1 函數內嵌套函數

# == 如果無法比較內容,就等效為 is
# 例如 函數對象 無法比較內容 就直接比較內存地址
def counter(base):
def _counter(step=1):
nonlocal base
base += step
return base
return _counter
f1 = counter(5)
f2 = counter(5)
print('f1 = {}, f2 = {}'.format(f1, f2))
print('f1_id = {}, f2_id = {}'.format(id(f1), id(f2)))
print('f1() = {}, f2() = {}'.format(f1(), f2()))
print('f1()_id = {}, f2()_id = {}'.format(id(f1()), id(f2())))
print(f1 == f2)
print(f1() == f2())
f1 = <function counter.<locals>._counter at 0x00000000078B13A8>, f2 = <function counter.<locals>._counter at 0x00000000078B1558>
f1_id = 126555048, f2_id = 126555480
f1() = 6, f2() = 6
f1()_id = 8791210553808, f2()_id = 8791210553808
False
True

1.4.2 函數內部返回全局函數

# == 如果無法比較內容,就等效為 is
# 例如 函數對象 無法比較內容 就直接比較內存地址
# 全局定義的函數,也就相當於一個全局變量,不管被賦值給多少變量,其 id 都是一樣的
inc_num = 100
def inc(step=1):
return inc_num+1
def counter(base=0):
print(id(inc))
return inc
print(1, inc, id(inc), id(inc()))
counter()
print(2, inc, id(inc), id(inc()))
f1 = counter(5)
f2 = counter(7)
print('f1 = {}, f2 = {}'.format(f1, f2))
print('f1_id = {}, f2_id = {}'.format(id(f1), id(f2)))
print('f1() = {}, f2() = {}'.format(f1(), f2()))
print('f1()_id = {}, f2()_id = {}'.format(id(f1()), id(f2())))
print(f1 == f2)
print(f1() == f2())
1 <function inc at 0x0000000008032C18> 134425624 8791210556816
134425624
2 <function inc at 0x0000000008032C18> 134425624 8791210556816
134425624
134425624
f1 = <function inc at 0x0000000008032C18>, f2 = <function inc at 0x0000000008032C18>
f1_id = 134425624, f2_id = 134425624
f1() = 101, f2() = 101
f1()_id = 8791210556816, f2()_id = 8791210556816
True
True

2、內建高階函數

2.1 排序 sorted

2.1.1 語法

  • sorted(iterable, /, *, key=None, reverse=False)
  • sorted函數是返回新列表
  • 注意與list.sort()(就地修改,返回結果是None)的區別

2.1.2 示例

  • sorted 函數 與 list sort 方法 的區別

    list1 = [1, 2, 3]
    list2 = sorted(list1, key=lambda x:6-x) # 不影響原列表,返回新列表
    print(list1, list2)
    # [1, 2, 3] [3, 2, 1]
    
    list1 = [1, 2, 3]
    list2 = list1.sort(key=lambda x:6-x) # 就地修改
    print(list1, list2)
    # [3, 2, 1] None
    
  • sorted 函數

    list3 = [1, 2, 3, 'a', 'b', 'A']
    list4 = sorted(list3, key=str)
    list5 = sorted(list3, key=str, reverse=True)
    for i in [list3, list4, list5]:
    print(i)
    for j in list3:
    print(ord(str(j)), end=' |=| ')
    
    [1, 2, 3, 'a', 'b', 'A']
    [1, 2, 3, 'A', 'a', 'b']
    ['b', 'a', 'A', 3, 2, 1]
    49 |=| 50 |=| 51 |=| 97 |=| 98 |=| 65 |=|
    
    # ord() 內建函數幫助
    Signature: ord(c, /)
    Docstring: Return the Unicode code point for a one-character string.
    Type: builtin_function_or_method
    

2.2 過濾 filter

2.2.1 語法

  • filter(self, /, *args, **kwargs)
  • filter(function or None, iterable) --> filter object
  • 對可迭代對象進行遍歷,返回一個迭代器
  • function參數是一個參數的函數,且返回值應該是bool類型,或其返回值等效布爾值
  • function參數如果是None,可迭代對象的每一個元素自身等效布爾值

2.2.2 示例

# 過濾出列表中既不能被3整除也不能被2整除的值
iter1 = filter(lambda x:x%3!=0 and x%2!=0, list(range(10)))
# 返回一個迭代器
print(iter1, type(iter1))
print(list(iter1))
<filter object at 0x0000000007B02E88> <class 'filter'>
[1, 5, 7]
# function 參數如果是`None`,可迭代對象的每一個元素自身等效布爾值
print(list(filter(None, range(5))))
print(list(filter(None, range(-5, 5))))
print(list(filter(None, [0, False, True, [], [1], {
}, {
1}])))
[1, 2, 3, 4]
[-5, -4, -3, -2, -1, 1, 2, 3, 4]
[True, [1], {
1}]
# if fn(element): yield element
print(list(filter(lambda x:True, range(5))))
print(list(filter(lambda x:False, range(5))))
print(list(filter(lambda x:None, range(5))))
[0, 1, 2, 3, 4]
[]
[]

2.3 映射 map

2.3.1 語法

  • map(self, /, *args, **kwargs)
  • map(func, *iterables) --> map object
  • 對多個可迭代對象的元素,按照指定的函數進行映射
  • 返回一個迭代器

2.3.2 示例

iter2 = map(lambda x:x+1, range(5))
print(iter2, type(iter2))
print(list(iter2))
<map object at 0x0000000007B295C8> <class 'map'>
[1, 2, 3, 4, 5]
print(list((map(lambda x:x**2, range(1,6)))))
print(dict((map(lambda x:(x, x**2), range(1,6)))))
print(dict((map(lambda x, y:(x, y**2), 'abcde', range(1,4)))))
[1, 4, 9, 16, 25]
{
1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{
'a': 1, 'b': 4, 'c': 9}
# set 集合是無序的
dict(map(lambda x,y:{
x, y}, 'abcde', range(10)))
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 'e': 4}

3、柯裡化

3.1 概念

  • 將原來接受多個參數的函數變成新的接受一個參數的過程的過程
  • 新的函數返回一個以原有第二個參數為參數的函數
  • 比如講 z=f(x, y) 轉為 z=f(x)(y)

3.2 示例

def add(x, y):
return x + y
add(4, 5)
# 9
def add(x):
def _add(y):
return x + y
return _add
add(4)(5)
# 9
def add(x, y, z):
return x + y + z
add(4, 5, 6)
# 15
def add(x):
def _add(y):
def _add1(z):
return x + y + z
return _add1
return _add
add(4)(5)(6)
# 15

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved