Python2.x_函數式編程

來源:互聯網
上載者:User

標籤:

變數可以指向函數,函數名也是變數

一 高階函數:參數包含函數

def add(a, b, f):

    print f(a)+f(b)

add(-3, 4, abs)

二 map函數:map(function, sequence, ...)

print map(lambda x:x*x, [0, 1, 2, 3, 4])  # [0, 1, 4, 9, 16]

三 reduce函數

reduce(function, sequence, initial), function必須只接受2個參數

reduce(f,[x1,x2,x3 x4])=f(f(x1,x2),x3),x4)

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]

def str2num(s):

    return reduce(lambda x,y:10*x+y, map(char2num, s))

print str2num(‘232891739‘)+1

四 filter函數

filter(function, sequence), function必須返回bool值

若function返回True則保留,返回False則過濾

def biggerthan5(x):

    return x>5

print filter(biggerthan5, [1,3,5,7,9])

五 sorted函數

sorted(iterable, cmp=None, key=None, reverse=False)

若reverse=False, 當cmp返回正數時,將左數移到右數右邊

def sortCriterion1(x,y):#從小到大 ,less

    if x>y:

        return 1

    elif x<y:

        return -1

    return 0

def sortCriterion2(x,y):#從大到小 ,greater

    if x>y:

        return -1

    elif x<y:

        return 1

    return 0

print u‘從小到大:‘,sorted([1,3,2], sortCriterion1)

print u‘從大到小:‘,sorted([1,3,2], sortCriterion2)

六 閉包函數:傳回值為函數

def name(s):

    def score(n):

        print s,‘your score is‘,n

    return score

n = name(‘Yoleimei‘)

n(100)

七 匿名函數lambda

lambda x,y: x*x+y*y == function(x,y){return x*x+y*y;} # in javascript

註:lambda運算式可嵌套,如 lambda fun1,fun2: lambda param: fun1(fun2(param))

def build(x, y):

    return lambda: x * x + y * y

f = build(3,5)

print f()

八 裝飾器Decorator:可以類比Decorator Design Pattern

def deco(fun):

    print ‘before calling fun()‘

    fun()

    print ‘after calling fun()‘

    return fun

@deco

def myFun():

    print ‘calling fun()‘

# console:

# before calling fun()

# calling fun()

# after calling fun()

九 偏函數:使部分參數預設化

import functools

def add(x, y):

    return x+y

myAdd = functools.partial(add, x=3, y=4)

print myAdd()

Python2.x_函數式編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.