zoukankan      html  css  js  c++  java
  • python lambda reduce yield isinstance

    lambda: 

    >>> f=lambda x,y,z:x+y+z
    >>> f(1,2,3)
    6
    >>> f=lambda x,y,z:x+y+x
    >>> f(1,2,3)
    4
    >>> 
    >>> n=5
    >>> reduce(lambda x,y:x*y,range(1,n+1))
    120
    >>> 
    >>> def action(x):
    ...     return lambda y:x+y
    ... 
    >>> a=action(2)
    >>> a(22)
    24
    >>> b=lambda x:lambda y:x+y
    >>> a=b(3)
    >>> a(2)
    5
    >>> (b(2))(2)
    4
    >>> 
    >>> 
    >>> n = 5
    >>> print reduce(lambda x, y: x * y, range(1, n + 1))
    120
    >>> 
    >>> m = 2
    >>> n = 5
    >>> print reduce( lambda x, y: x * y, range( 1, n + 1 ), m )  # 240
    240

    >>> map( lambda x: x*x, [y for y in range(10)] )
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    reduce:

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

    >>> def add(x, y):
    ...     return x + y
    ... 
    >>> reduce(add, [1, 3, 5, 7, 9])
    25

    yield:

    ## yield 解释器会将其视为一个 generator 返回一个 iterable 对象

    >>> def fab(max): 
    ...     n, a, b = 0, 0, 1 
    ...     while n < max: 
    ...         yield b 
    ...         # print b 
    ...         a, b = b, a + b 
    ...         n = n + 1 
    ... 
    >>> for n in fab(5):
    ...     print n
    ... 
    1
    1
    2
    3
    5
    def _filter_one(obj, spec_obj):
        return True
    
    def filter_all(filter_obj_list, spec_obj):
        for obj in filter_obj_list:
            if _filter_one(obj, spec_obj):
                yield obj
    
    filter_obj_list=[1,2,3]
    spec_obj=None
    
    print list(filter_all(filter_obj_list,spec_obj))
    
    # python test.py
    [1, 2, 3]

    isinstance:

    #推荐实用判断type的时候实用isinstance而非type,理由如下,自定义的type判断可能不准确

    >>> class A():
    ...     pass
    ... 
    >>> class B():
    ...     pass
    ... 
    >>> a = A()
    >>> b = B()
    >>> print(type(a) is type(b))
    True
    >>> print(isinstance(type(a),type(b)))
    False
  • 相关阅读:
    C#之集合常用扩展方法与Linq
    PHP核心之MVC设计模式
    Javascript高级之变量
    Javascript高级之console调试
    Javascript高级之概述
    MySQL数据库之PDO扩展
    MySQL数据库之MySQL扩展
    MySQL数据库之数据库备份与还原
    MySQL数据库之预处理
    MySQL数据库之函数
  • 原文地址:https://www.cnblogs.com/yaoweilei/p/7509881.html
Copyright © 2011-2022 走看看