# -*- coding: utf-8 -*-
#python 常用高階函式
deffac
(n):
'''return n! zw'''
return
1if n <
2else n*fac(n-1)
print
(fac.__doc__)
fa=fac
a=list
(map
(fa,
range(5
)))# map 函式把每個元素都放到fa這個函式裡面執行,並且是乙個迭代器,就算外面必須用list才能顯示出來
print
('this is origin a:'
,a)b=
sorted
(a,reverse=
true
)# sorted 把a的排序後的結果複製給b 但是並沒有改變a
print
('this is a using sorted '
,b)print
('this is a by using sorted :'
,a)c=
list
.sort(a,reverse=
true
)#list.sort只改變a的排序值 並不會把值返回給c
print
('this is c'
,c)print
('this is a by using list sort'
,a)#sort 可以對字元長度排序
fruit =
['b'
,'dbc'
,'eb'
,'abcdef'
,'gbcd'
]sorted_fruit =
sorted
(fruit)
print
('預設字元按照字母順序排序:'
,sorted_fruit)
sorted_len_fruit =
sorted
(fruit,key=
len)
print
('按照字元的長度排序'
,sorted_len_fruit)
compound =
list
(map
(fa,
filter
(lambda n:n%3,
range(6
))))
print
('多個高階函式的混用:'
,compound)
輸出結果如下
return n! zw
this is origin a:[1
,1,2
,6,24
]this is a using sorted[24
,6,2
,1,1
]this is a by using sorted:[
1,1,
2,6,
24]this is c none
this is a by using list sort [24,
6,2,
1,1]
預設字元按照字母順序排序: [
'abcdef'
,'b'
,'dbc'
,'eb'
,'gbcd'
]按照字元的長度排序 [
'b',
'eb'
,'dbc'
,'gbcd'
,'abcdef'
]多個高階函式的混用: [1,
2,24,
120]
process finished with exit code 0
Python常用高階函式
高階函式是在python中乙個非常有用的功能函式,所謂高階函式就是乙個函式可以用來接收另乙個函式作為引數,這樣的函式叫做高階函式。為了便於理解,我們從實際例子來看看函式當做引數被傳遞到另個函式是什麼樣的。我們把abs 函式賦值給了f變數,接下來你就可以像使用abs 函式本身那樣使用f變數了,區別只是...
python 內建常用高階函式
一 函式式程式設計 1 map 是 python 內建的高階函式,它接收乙個函式 f 和乙個 list,並通過把函式 f 依次作用在 list 的每個元素上,得到乙個新的 list 並返回 def add x return x x print map add,1,2,3 2 reduce 函式也是p...
python 函式高階 python 函式高階
形參角度 萬能引數 動態接收位置引數 args 動態接收關鍵字引數 kwargs 的魔性用法 函式定義時 代表聚合。他將所有的位置引數 聚合成乙個元組,賦值給了args 函式定義時 將所有的關鍵字引數聚合成乙個字典中,將這個字典賦給了 kwargs 和 在函式的呼叫時 代表打散 僅限關鍵字引數 de...