zoukankan      html  css  js  c++  java
  • Python的函数以及函数式编程

    Python的函数以及函数式编程

     

     

    1. 列表解析语法:[expr for iter_var in iterable] 或 [expr for iter_var in iterable if cond_expr]

    说明:

    第一种语法:首先迭代iterable里所有内容,每一次迭代,都把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算值生成一个列表。

    第二种语法:加入了判断语句,只有满足条件的内容才把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算值生成一个列表。

    举例:

    >>> [i + 1 for i in range(10)]

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    1. 函数参数组:

    Func(*tuple_grp_nonkw_args, **dict_grp_kw_args)

    例子:http://www.corepython.com/

    #!/usr/bin/env python

    from operator import add, sub

    from random import randint, choice

    ops = {'+': add, '-': sub}

    MAXTRIES = 2

    def doprob():

        op = choice('+-')

        nums = [ randint(1,10) for i in range(2) ]

        nums.sort(reverse=True)

        ans = ops[op](*nums)

        pr = '%d %s %s = ' % (nums[0], op, nums[1])

        oops = 0

        while True:

            try:

                if int(raw_input(pr)) == ans:

                    print 'correct'

                    break

                if oops == MAXTRIES:

                    print 'sorry... the answer is %s%d' % (pr, ans)

                else:

                    print 'incorrect... try again'

                    oops += 1

            except (KeyboardInterrupt,

                    EOFError, ValueError):

                print 'invalid input... try again'

    def main():

        while True:

            doprob()

            try:

                opt = raw_input('Again? [y] ').lower()

                if opt and opt[0] == 'n':

                    break

            except (KeyboardInterrupt, EOFError):

                break

    if __name__ == '__main__':

        main()

    1. 内部函数:

    定义:在函数内创建另外一个函数,叫做“内部/内嵌函数”

    1. 闭包:

    如果内部函数的定义包含了在外部函数里面定义的对象的引用,内部函数--à闭包(closure)。

    1. *函数(与方法)装饰器:

    装饰器就是相当于在既有的函数中封装了一段代码,但是调用的时候还是调用原函数,只是用装饰器的语法将新的需要操作的代码实现为一个装饰器的装饰函数后写在前面就好了。但是装饰器的必须调用原函数,否则原函数不会执行。

    装饰器以@开头, 是函数在调用上的修饰

    @decorator(dec_opt_args)

    Def func2Bdecorated(dec_opt_args):

    Eg:

    #!/usr/bin/env python
     
    from time import ctime, sleep
     
    def tsfunc(func):
        def wrappedFunc():
            print '[%s] %s() called' % (
                ctime(), func.__name__)
            return func()
        return wrappedFunc
     
    @tsfunc
    def foo():
        pass
     
    foo()
    sleep(4)
     
    for i in range(2):
        sleep(1)
        foo()
    1. 抓取网页到本地文件:

    #!/usr/bin/env python

    from urllib import urlretrieve

    def firstNonBlank(lines):

        for eachLine in lines:

            if not eachLine.strip():

                continue

            else:

                return eachLine

    def firstLast(webpage):

        f = open(webpage)

        lines = f.readlines()

        f.close()

        print firstNonBlank(lines),

        lines.reverse()

        print firstNonBlank(lines),

    def download(url='http://192.168.99.240:62268/dokuwiki/doku.php', process=firstLast):

        try:

            retval = urlretrieve(url)[0]

            print type(retval)

        except IOError:

            retval = None

        if retval:             # do some processing

            process(retval)

    if __name__ == '__main__':

    download()

    1. 定义“可变长参数”的函数:

    采用*vargs_tuple 或 **vargs_dict

    Def func([formal_args,] *tuple)

    Def func([formal_args,] [*tuple,] **dict)

    1. 函数式编程:

    测试函数的函数例子。

    #!/usr/bin/env python

    def testit(func, *nkwargs, **kwargs):

       try:

           retval = func(*nkwargs, **kwargs)

           result = (True, retval)

       except Exception, diag:

           result = (False, str(diag))

       return result

    def test():

        funcs = (int, long, float)

        vals = (1234, 12.34, '1234', '12.34')

        for eachFunc in funcs:

            print '-' * 20

            for eachVal in vals:

                retval = testit(eachFunc,

                                eachVal)

                if retval[0]:

                    print '%s(%s) =' %

        (eachFunc.__name__, `eachVal`), retval[1]

                else:

                    print '%s(%s) = FAILED:' %

        (eachFunc.__name__, `eachVal`), retval[1]

    if __name__ == '__main__':

        test()

  • 相关阅读:
    149. Max Points on a Line(js)
    148. Sort List(js)
    147. Insertion Sort List(js)
    146. LRU Cache(js)
    145. Binary Tree Postorder Traversal(js)
    144. Binary Tree Preorder Traversal(js)
    143. Reorder List(js)
    142. Linked List Cycle II(js)
    141. Linked List Cycle(js)
    140. Word Break II(js)
  • 原文地址:https://www.cnblogs.com/bibaodi/p/6481216.html
Copyright © 2011-2022 走看看