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