python (4)函式式程式設計 高階函式

2021-09-28 16:00:45 字數 4933 閱讀 3656

函式名也是變數

>>> abs = 10

>>> abs(-10)

traceback (most recent call last):

file "", line 1, in typeerror: 'int' object is not callable

函式本身也可以賦值給變數,即:變數可以指向函式。

>>> f = abs

>>> f

>>> f = abs

>>> f(-10)

10

把函式作為引數傳入,這樣的函式稱為高階函式,函式式程式設計就是指這種高度抽象的程式設計正規化。

>>> def add(x, y, f):

return f(x) + f(y)

>>> add(-5, -6, abs)

11

編寫高階函式,就是讓函式的引數能夠接收別的函式。

map()函式接收兩個引數,乙個是函式,乙個是iterablemap將傳入的函式依次作用到序列的每個元素,並把結果作為新的iterator返回。

>>> def f(x):

... return x * x

...>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> list(r)

[1, 4, 9, 16, 25, 36, 49, 64, 81]

map()作為高階函式,事實上它把運算規則抽象了,因此,我們不但可以計算簡單的f(x)=x^2,還可以計算任意複雜的函式,比如,把這個list所有數字轉為字串:

>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

['1', '2', '3', '4', '5', '6', '7', '8', '9']

reduce把乙個函式作用在乙個序列[x1, x2, x3, ...]上,這個函式必須接收兩個引數,reduce把結果繼續和序列的下乙個元素做累積計算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> from functools import reduce

>>> def fn(x, y):

... return x * 10 + y

...>>> reduce(fn, [1, 3, 5, 7, 9])

13579

把使用者輸入的不規範的英文名字,變為首字母大寫,其他小寫的規範名字。

>>> l1 = ['adam', 'lisa', 'bart']

>>> def normalize(name):

return name[:1].upper() + name[1:].lower()

>>> l2 = list(map(normalize, l1))

>>> print(l2)

['adam', 'lisa', 'bart']

請編寫乙個prod()函式,可以接受乙個list並利用reduce()求積:

def prod(l):

def multiply(x,y):

return x*y

return reduce(multiply,l)

利用mapreduce編寫乙個str2float函式,把字串'123.456'轉換成浮點數123.456

from functools import reduce

digits =

def str2float(s):

l = s.split('.')

def fn(x, y):

return x * 10 + y

def char2num(s):

return digits[s]

return reduce(fn ,map(char2num ,l[0])) + reduce(fn, map(char2num, l[1]))/(pow(10, len(l[1])))

split() 方法語法:

str.split(str="", num=string.count(str)).

# 引數

str -- 分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等。

num -- 分割次數。預設為 -1, 即分隔所有。

# 返回值

# 返回分割後的字串列表。

filter()也接收乙個函式和乙個序列。和map()不同的是,filter()把傳入的函式依次作用於每個元素,然後根據返回值是true還是false決定保留還是丟棄該元素。

例如,在乙個list中,刪掉偶數,只保留奇數,可以這麼寫:

def is_odd(n):

return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))

# 結果: [1, 5, 9, 15]

把乙個序列中的空字串刪掉,可以這麼寫:

def not_empty(s):

return s and s.strip()

list(filter(not_empty, ['a', '', 'b', none, 'c', ' ']))

# 結果: ['a', 'b', 'c']

>>> 'a' and 'b'

'b'>>> '' and 'b'

''>>> 'b' and ''

''>>> 'a' and 'b' and 'c'

'c'>>> '' and none and 'c'

''

在布林上下文中從左到右演算表示式的值,如果布林上下文中的所有值都為真,那麼 and 返回最後乙個值。

如果布林上下文中的某個值為假,則 and 返回第乙個假值。

請利用filter()篩選出回數:

def is_palindrome(n):#篩選器

s=str(n)

if(len(s)<=1):

return true

else:

return s[0]==s[-1] and is_palindrome(s[1:-1])

>>> sorted(['bob', 'about', 'zoo', 'credit'])

['credit', 'zoo', 'about', 'bob']

預設情況下,對字串排序,是按照ascii的大小比較的,由於'z' < 'a',結果,大寫字母z會排在小寫字母a的前面。

現在,我們提出排序應該忽略大小寫,按照字母序排序。要實現這個演算法,不必對現有**大加改動,只要我們能用乙個key函式把字串對映為忽略大小寫排序即可。忽略大小寫來比較兩個字串,實際上就是先把字串都變成大寫(或者都變成小寫),再比較。

這樣,我們給sorted傳入key函式,即可實現忽略大小寫的排序:

>>> sorted(['bob', 'about', 'zoo', 'credit'], key=str.lower)

['about', 'bob', 'credit', 'zoo']

要進行反向排序,不必改動key函式,可以傳入第三個引數reverse=true

>>> sorted(['bob', 'about', 'zoo', 'credit'], key=str.lower, reverse=true)

['zoo', 'credit', 'bob', 'about']

假設我們用一組tuple表示學生名字和成績:

l = [('bob', 75), ('adam', 92), ('bart', 66), ('lisa', 88)]
請用sorted()對上述列表分別按名字排序:

>>> def by_name(n):

return n[0]

>>> l2 = sorted(l, key = by_name)

>>> print(l2)

[('adam', 92), ('bart', 66), ('bob', 75), ('lisa', 88)]

再按成績從高到低排序:

>>> def by_score(n):

return n[1]

>>> l2 = sorted(l, key = by_score)

>>> print(l2)

[('bart', 66), ('bob', 75), ('lisa', 88), ('adam', 92)]

python 4函式式程式設計

1 高階函式 變數可以指向函式。def add x,y,f 例如f引數為函式 編寫高階函式,就是讓函式的引數能夠接收別的函式。python內建了map 和reduce 高階函式。1.1 將list每項相乘 def f x return x x r map f,1,2,3,4,5,6,7 list r...

python函式式程式設計模式 python函式式程式設計

1 callable內建函式判斷乙個名字是否為乙個可呼叫函式 import math x 1 y math.sqrt callable x false callable y true 2 記錄函式 文件字串 def square x calculates the square of number x...

python函式式程式設計模式 Python函式式程式設計

函式式程式設計就是一種抽象程度很高的程式設計正規化,純粹的函式式程式語言編寫的函式沒有變數,因此,任意乙個函式,只要輸入是確定的,輸出就是確定的,這種純函式我們稱之為沒有 而允許使用變數的程式語言,由於函式內部的變數狀態不確定,同樣的輸入,可能得到不同的輸出,因此,這種函式是有 的。函式式程式設計的...