1. 程式人生 > >Python 函數式編程

Python 函數式編程

每次 構造 高級 轉換成 偏函數 sort 結果 變為首字母大寫 ext

4.函數式編程

4.11高級函數

map接收2個參數,1個是函數對象本身,一個是Iterable

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

##reduce把結果繼續和序列的下一個元素做累積計算

def f(x):

... return x * x

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

...

>>> def char2num(s):

... return {‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}[s]

...

>>> reduce(fn, map(char2num, ‘13579‘)) #輸出int 13579

--------------

利用map()函數,把用戶輸入的不規範的英文名字,變為首字母大寫,其他小寫的規範名字。

輸入:[‘adam‘, ‘LISA‘, ‘barT‘],輸出:[‘Adam‘, ‘Lisa‘, ‘Bart‘]:

def normalize(name):

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

L=[‘adam‘, ‘LISA‘, ‘barT‘]

list(map(normalize,L))

------------

Python提供的sum()函數可以接受一個list並求和,請編寫一個prod()函數,可以接受一個list並利用reduce()求積:

print(‘3 * 5 * 7 * 9 =‘, prod([3, 5, 7, 9]))

from functools import reduce

def prod(L):

def multi(x,y)

return x*y

return reduce(multi,L)

--------------

利用map和reduce編寫一個str2float函數,把字符串‘123.456‘轉換成浮點數123.456:

# -*- coding: utf-8 -*-

from functools import reduce

def str2float(s):

print(‘str2float(\‘123.456\‘) =‘, str2float(‘123.456‘))

4.1.2 高階函數filter:

和map()類似,filter()也接收一個函數和一個序列。filter()把傳入的函數依次作用於每個元素,然後根據返回值是True還是False決定保留還是丟棄該元素。

def is_odd(n):

return n % 2 == 1

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

#結果是奇數 filter()的作用是從一個序列中篩出符合條件的元素。由於filter()使用了惰性計算,所以只有在取filter()結果的時候,才會真正篩選並每次返回下一個篩出的元素

---------------------

計算素數的一個方法是埃氏篩法

1.用Python來實現這個算法,可以先構造一個從3開始的奇數序列:

def _odd_iter():

n = 1

while True:

n = n + 2

yield n

2.然後定義一個篩選函數:

def _not_divisible(n):

return lambda x: x % n > 0

3.定義一個生成器,不斷返回下一個素數:先返回第一個素數2

def primes():

yield 2

it = _odd_iter() # 初始序列

while True:

n = next(it) # 返回序列的第一個數

yield n

it = filter(_not_divisible(n), it) # 構造新序列

4.由於primes()也是一個無限序列,所以調用時需要設置一個退出循環的條件:

for n in primes():

if n < 1000:

print(n)

else:

break

?回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()濾掉非回數:

4.1.3排序算法 sorted

sorted([36, 5, -12, 9, -21], key=abs)

[5, 9, -12, -21, 36] #可以接收一個key函數來實現自定義的排序,例如按絕對#值大小排序:

>>> sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower)

[‘about‘, ‘bob‘, ‘Credit‘, ‘Zoo‘] #一個key函數把字符串映射為忽略大小寫排序即可

#要進行反向排序,不必改動key函數,可以傳入第三個參數reverse=True:

>>> sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower,reverse=True)

[‘Zoo‘, ‘Credit‘, ‘bob‘, ‘about‘]

4.2返回函數

高階函數除了可以接受函數作為參數外,也可把函數作為結果返回

def lazy_sum(*args):

def sum():

ax = 0

for n in args:

ax = ax + n

return ax

return sum

#閉包 :當lazy_sum返回函數sum時,相關參數和變量都保存在返回的函數中

def count():

fs = []

for i in range(1, 4):

def f():

return i*i

fs.append(f)

return fs

f1, f2, f3 = count()

------------

def count():

def f(j):

def g():

return j*j

return g

fs = []

for i in range(1, 4):

fs.append(f(i)) # f(i)立刻被執行,因此i的當前值被傳入f()

return fs

4.3 匿名函數

>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

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

-----

4.4 裝飾器

-------

4.5 偏函數

int2=functool.partical(int ,base=2)

int2(‘10010‘)#字符串轉int,在轉二進制

Python 函數式編程