美文网首页
python 中一些方法小记

python 中一些方法小记

作者: McDu | 来源:发表于2017-06-23 19:52 被阅读13次

    ['a\n'].strip() 可以去掉'\n'


    map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    
    def add(x, y):
         return x + y  
    reduce(add, [1, 3, 5, 7, 9]) ##25
    

    删除100以内的素数:

    def f(x):
        if x == 1:
            return True
        else:
            for i in range(2,x):
                if x%i ==0:
                    return True
            return False
    
    print filter(f,range(1,101))
    

    返回闭包时牢记的一点就是:返回函数不要引用任何循环变量,或者后续会发生变化的变量。

    def count():
        fs = []
        for i in range(1, 4):
            def f():
                 return i*i
            fs.append(f)
        return fs
    
    f1, f2, f3 = count()  ## 9,9,9
    

    如果一定要引用循环变量怎么办?方法是再创建一个函数,用该函数的参数绑定循环变量当前的值,无论该循环变量后续如何更改,已绑定到函数参数的值不变:

    >>> def count():
    ...     fs = []
    ...     for i in range(1, 4):
    ...         def f(j):
    ...             def g():
    ...                 return j*j
    ...             return g
    ...         fs.append(f(i))
    ...     return fs
    ... 
    >>> f1, f2, f3 = count()
    >>> f1()
    1
    >>> f2()
    4
    >>> f3()
    9
    

    匿名函数lambda x: x * x实际上就是:

    def f(x):
        return x * x
    

    匿名函数只能有一个表达式,不用写return,返回值就是该表达式的结果。

    相关文章

      网友评论

          本文标题:python 中一些方法小记

          本文链接:https://www.haomeiwen.com/subject/flmufxtx.html