def ds(x): return 2 * x + 1 ds(5) ---11 g = lambda x : 2 * x + 1 g(5) ---11 def add(x,y): return x + y add(3,4) ---7 g = lambda x,y : x + y g(3,4) ---7
經常使用的內置函數(BIF函數)python
list (filter(None,[1,0,False,True])) ---[1, True] #把任何非True的內容給過濾掉了 #利用filter寫一個奇數的過濾器 def odd(x): return x % 2 temp = range(10) show = filter(odd,temp) list(show) ---[1,3,5,7,9] list (filter(lambda x : x % 2 , range(10))) ---[1,3,5,7,9] def aaa(x): return x % 2 == 1 ret = list(filter(aaa, [1, 2, 54, 3, 6, 8, 17, 9])) print(ret) ---[1, 3, 17, 9]
l = [15, 24, 31, 14] def func(x): return x > 20 print(list(filter(func,l))) print(list(filter(lambda x: x > 20, l))) # 比較二者差別
②map() -----映射數組
list(map(lambda x : x * 2, range(10))) ---[0, 2, 4, 6, 8, 10, 12, 14, 16, 18
l = [1, 2, 3, 4, 5] def pow2(x): return x*x print(list(map(pow2, l))) ---[1, 4, 9, 16, 25]
l = [1, 2, 3, 4] def func(x): return x*x print(list(map(func, l))) print(list(map(lambda x : x*x, l))) # 比較二者差別
# 多個數組進行相加
li = [11, 22, 33] sl = [1, 2, 3] new_list = map(lambda a, b: a + b, li, sl) print(new_list)
---[12, 24, 36] # 這裏在py2中結果是這個,在py3中是一個可迭代對象,須要調用list函數
③ reduce()函數函數
也是存在兩個參數,一個函數,一個可迭代序列,可是函數必須接收兩個參數。做用是對於序列內全部元素進行累積操做spa
from functools import reduce # 在py2中不須要從functools中導入,可是在py3中須要,他已經不屬於一個內置函數,屬於一個高階函數 lst = [11,22,33] func2 = reduce(lambda arg1,arg2:arg1+arg2,lst) print('func2:', func2) ---func2: 66
例題:code
# 現有兩個元組(('a'),('b')),(('c'),('d')),請使用python中匿名函數生成列表[{'a':'c'},{'b':'d'}] # 方法一 t1 = (('a'), ('b')) t2 = (('c'), ('d')) print(list(zip(t1, t2))) # [('a', 'c'), ('b', 'd')] print(list(map(lambda t: {t[0], t[1]}, zip(t1, t2)))) # [{'a', 'c'}, {'d', 'b'}] # 方法二 print(list([{i,j} for i,j in zip(t1,t2)])) # [{'a', 'c'}, {'d', 'b'}] #方法三 func = lambda t1,t2:[{i,j} for i,j in zip(t1,t2)] ret = func(t1,t2) print(ret) # [{'a', 'c'}, {'d', 'b'}]