Python 函數式編程

來源:互聯網
上載者:User

標籤:浮點數   篩選   條件   輸出   prime   sort   about   依次   使用者   

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 函數式編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.