函數式編程能夠使代碼更加簡潔,易於理解。Python提供的常見函數式編程方法以下:python
#list(range(1,11)) 結果爲[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x = [item for item in range(1,8)] print(x)
[1, 2, 3, 4, 5, 6, 7]
x = [item for item in range(1,8) if item % 2 == 0] print(x)
[2, 4, 6]
area = [(x,y) for x in range(1,5) for y in range(1,5) if x!=y] print(area)
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
dict(area) # 採用字典對area列表打包,相同的鍵的元素,後面覆蓋前面的鍵
{1: 4, 2: 4, 3: 4, 4: 3}
['The number: %s' % n for n in range(1,4)]
['The number: 1', 'The number: 2', 'The number: 3']
dict1 = {'1':'A','2':'B','3':'C','4':'D'} [k + '=' + v for k, v in dict1.items()]
['1=A', '2=B', '3=C', '4=D']
lambda x,y: x*y
<function __main__.<lambda>>
(lambda x,y: x*y)(9,9)
81
f = lambda x,y: x/y f(10,2)
5.0
list(map(lambda x : x**3,[1,2,3,4]))
[1, 8, 27, 64]
list(map(lambda x,y:x+y, [1,2,3,4],[4,5,6,7]))
[5, 7, 9, 11]
from functools import reduce reduce((lambda x,y:x+y), [1,2,3,4]) # 等價於 1+2+3+4
10
reduce((lambda x,y:x+y), [1,2,3,4], 90) # 等價於 90+1+2+3+4
100
reduce((lambda x,y:x/y), [1,2,3,4,5]) # 等價於 1/2/3/4/5=1/120
0.008333333333333333
list(filter(None,[11,1,2,0,0,0,False,True]))
[11, 1, 2, True]
list(filter(lambda x:x%2, range(1,11)))
[1, 3, 5, 7, 9]
list(filter(lambda x: x.isalpha(),'a11b22c33d44'))
['a', 'b', 'c', 'd']
tuple(filter(lambda x: x.isalpha(),'a11b22c33d44'))
('a', 'b', 'c', 'd')
set(filter(lambda x: x.isalpha(),'a11b22c33d44'))
{'a', 'b', 'c', 'd'}
list(filter(lambda x:x>4, [1,2,3,4,5,6,7]))
[5, 6, 7]
set(filter(lambda x:x>4, [1,2,3,4,5,6,7]))
{5, 6, 7}
x1 = [1, 2, 3, 4] z = zip(x1) print(type(z)) print(list(z))
<class 'zip'> [(1,), (2,), (3,), (4,)]
x1 = [1,2,3,4,5] x2 = [6,7,8,9,10] z1 = zip(x1,x2) print(list(z1))
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]