Python - 內置函數 選例
概覽參見 https://www.runoob.com/python/python-built-in-functions.html
官方文檔 https://docs.python.org/3/library/functions.html?highlight=built#ascii
0. 高階函數
滿足倆個特性任意一個即為高階函數
1.函數的傳入參數是一個函數名
2.函數的返回值是一個函數名
1. map() 函數
map
(function, iterable, ...) 即接收兩種參數,函數 f 和 可叠代對象, map將傳入的函數依次作用到序列的每個元素,返回的為叠代對象map類型。
用法舉例:
num1 = [1, 2, 4, 7, 11] # lambda x: x+1 def add(x): return x+1 # lambda x: x**2 def pf(x): return x**2 def map_test(func, array): num2 = [] for i in array: res = func(i) num2.append(res) return num2 ret = map_test(lambda x: x+1, num1) print(ret) rett = map_test(lambda x: x**2, num1) print(rett) rettt = map(lambda x:x+1, num1) # 第一個參數為可用匿名函數或者有名函數,第二個參數為可叠代對象,返回值為可叠代對象 print(rettt) retttt = list(rettt) print(retttt) name = "helloworld" s = list(map(lambda x:x.upper(), name)) print(s) =============== [2, 3, 5, 8, 12] [1, 4, 16, 49, 121] <map object at 0x00000000022FAAC8> [2, 3, 5, 8, 12] [‘H‘, ‘E‘, ‘L‘, ‘L‘, ‘O‘, ‘W‘, ‘O‘, ‘R‘, ‘L‘, ‘D‘]
2. filter() 函數
filter
(function, iterable) filter()函數接收一個函數 f 和一個可叠代對象,這個函數 f 的作用是對每個元素進行判斷,返回 True或 False,filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新的可叠代對象。
用法舉例:
people = [‘m_zhangsan_sb‘, ‘lisi‘, ‘m_wangwu_sb‘, ‘chenliu‘] # lambda x:x.endswith(‘sb‘) def end(n): return n.endswith(‘sb‘) def filter_test(func, array): ret = [] for i in array: if func(i): ret.append(i) return ret a = filter_test(lambda x:x.endswith(‘sb‘), people) print(a) l = list(filter(lambda x: x.endswith(‘sb‘), people)) print(l) =============== [‘m_zhangsan_sb‘, ‘m_wangwu_sb‘] [‘m_zhangsan_sb‘, ‘m_wangwu_sb‘]
3. reduce() 函數
reduce()函數接收的參數和 map()類似,一個函數 f,一個list,但行為和 map()不同,reduce()傳入的函數 f 必須接收兩個參數,reduce()對list的每個元素反復調用函數f,並返回最終結果值。
例如,編寫一個f函數,接收x和y,返回x和y的和:
1 2 |
def f(x, y):
return x + y
|
調用 reduce(f, [1, 3, 5, 7, 9])時,reduce函數將做如下計算:
1 2 3 4 5 |
先計算頭兩個元素:f( 1 , 3 ),結果為 4 ;
再把結果和第 3 個元素計算:f( 4 , 5 ),結果為 9 ;
再把結果和第 4 個元素計算:f( 9 , 7 ),結果為 16 ;
再把結果和第 5 個元素計算:f( 16 , 9 ),結果為 25 ;
由於沒有更多的元素了,計算結束,返回結果 25 。
|
上述計算實際上是對 list 的所有元素求和。雖然Python內置了求和函數sum(),但是,利用reduce()求和也很簡單。
reduce()還可以接收第3個可選參數,作為計算的初始值。如果把初始值設為100,計算:
1 |
reduce (f, [ 1 , 3 , 5 , 7 , 9 ], 100 )
|
結果將變為125,因為第一輪計算是:
計算初始值和第一個元素:f(100, 1),結果為101。
用法舉例:
num1 = [1,2,3,4] def reduce_test(func, array, init=None): if init == None: res = array.pop(0) else: res = init for i in array: res = func(res, i) return res a = reduce_test(lambda x,y:x*y, num1) print(a) # 先導入庫 from functools import reduce b = reduce(lambda x,y:x*y, num1, 100) print(b) ============ 24 2400
4. zip() 函數
zip
(*iterables)
zip函數接受任意多個(包括0個和1個)序列作為參數,返回一個tuple列表。具體意思不好用文字來表述,直接看示例:
1.示例1:
x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] xyz = zip(x, y, z) print xyz
運行的結果是:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
從這個結果可以看出zip函數的基本運作方式。
2.示例2:
x = [1, 2, 3] y = [4, 5, 6, 7] xy = zip(x, y) print xy
運行的結果是:
[(1, 4), (2, 5), (3, 6)]
從這個結果可以看出zip函數的長度處理方式。
3.示例3:
x = [1, 2, 3] x = zip(x) print x
運行的結果是:
[(1,), (2,), (3,)]
從這個結果可以看出zip函數在只有一個參數時運作的方式。
4.示例4:
x = zip() print x
運行的結果是:
[]
從這個結果可以看出zip函數在沒有參數時運作的方式。
5.示例5:
x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] xyz = zip(x, y, z) u = zip(*xyz) print u
運行的結果是:
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
一般認為這是一個unzip的過程,它的運行機制是這樣的:
在運行zip(*xyz)之前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
那麽,zip(*xyz) 等價於 zip((1, 4, 7), (2, 5, 8), (3, 6, 9))
所以,運行結果是:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
註:在函數調用中使用*list/tuple的方式表示將list/tuple分開,作為位置參數傳遞給對應函數(前提是對應函數支持不定個數的位置參數)
6.示例6:
x = [1, 2, 3] r = zip(* [x] * 3) print r
運行的結果是:
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
它的運行機制是這樣的:
[x]生成一個列表的列表,它只有一個元素x
[x] * 3生成一個列表的列表,它有3個元素,[x, x, x]
zip(* [x] * 3)的意思就明確了,zip(x, x, x)
5. max() min() 函數 (跟sort()可類比)
max(iterable, key, default) 求叠代器的最大值,其中iterable 為叠代器,max會for i in … 遍歷一遍這個叠代器,然後將叠代器的每一個返回值當做參數傳給key=func 中的func(一般用lambda表達式定義) ,然後將func的執行結果傳給key,然後以key為標準進行大小的判斷。
以下根據不同的判斷條件返回最大值也不同
d1 = {‘name‘: ‘egon‘, ‘price‘: 100} d2 = {‘name‘: ‘rdw‘, ‘price‘: 666} d3 = {‘name‘: ‘zat‘, ‘price‘: 1} l1 = [d1, d2, d3] a = max(l1, key=lambda x: x[‘name‘]) print(a) b = max(l1, key=lambda x: x[‘price‘]) print(b)
===================
{‘name‘: ‘zat‘, ‘price‘: 1}
{‘name‘: ‘rdw‘, ‘price‘: 666}
people = [ {‘name‘: ‘zs‘, ‘age‘: 1}, {‘name‘: ‘ls‘, ‘age‘: 2}, {‘name‘: ‘ww‘, ‘age‘: 6}, {‘name‘: ‘cl‘, ‘age‘: 4} ] a = max(people, key=lambda dic:dic[‘age‘]) print(a) ================= {‘name‘: ‘ww‘, ‘age‘: 6}
Python - 內置函數 選例