python 四大利器
filter()
and map()
and reduce()
and lambda()
filter(function, iterable)¶
filter(function, iterable)
is equivalent to [item for item in iterable if function(item)]
if function is not None
and [item for item in iterable if item]
if function is None
.
see https://docs.python.org/2/library/functions.html?highlight=filter#filter
对迭代器中function(iter)
为True
的组成一个新的迭代器(list/string/tuple
等,取决于迭代器的类型)。
1 2 3 4 5 6 7 8 9 | >>> def f(x): return x % 2 != 0 and x % 3 !=0 >>> filter(f,xrange(1,100)) [1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97] # or >>> filter(lambda x: x % 2 != 0 and x % 3 !=0, xrange(1,100)) [1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97] # or >>> [ x for x in xrange(1,100) if x % 2 != 0 and x % 3 !=0] [1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97] |
map(function, iterable, ...)¶
Apply function to every item of iterable and return a list of the results.
1 2 3 4 5 6 7 8 9 10 | >>> def cube(x): return x*x*x >>> map(cube, xrange(0, 10)) [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] # or >>> map(lambda x: x*x*x, xrange(0, 10)) # or >>> [x*x*x for x in xrange(0, 10)] # for multiple iterable >>> map(lambda x,y: x+ y, xrange(0, 10), xrange(10, 20)) [10, 12, 14, 16, 18, 20, 22, 24, 26, 28] |
reduce(function, iterable[, initializer])¶
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
For example, reduce(lambda x, y: x+y, [1,2, 3, 4, 5])
calculates ((((1+2)+3)+4)+5)
.
1 2 3 4 5 | >>> def add(x,y): return x + y >>> reduce(add, xrange(1, 11)) 55 >>> reduce(add, xrange(1, 11),20) 75 |
lambda¶
lambda
是Python中一种非常有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda
的函数,是从LISP
借用来的,可以用在任何需要函数的地方,函数式编程的典范。
其实上面已经不自觉地在使用了,懒人必备。
1 2 3 4 | >>> g = lambda x: x*x*x >>> g(3) 27 >>> (lambda x: x*x*x)(3) |
综合运用¶
我们也可以把filter
map
reduce
lambda
结合起来用,函数就可以简单的写成一行。
1 2 3 4 5 | >>> filter(lambda x: x % 3 != 0 and x % 4 !=0, map(lambda x,y: x+ y, xrange(0, 100), xrange(100, 200))) [106, 110, 118, 122, 130, 134, 142, 146, 154, 158, 166, 170, 178, 182, 190, 194, 202, 206, 214, 218, 226, 230, 238, 242, 250, 254, 262, 266, 274, 278, 286, 290, 298] # 再求和试试 >>> reduce(lambda a,b:a+b, filter(lambda x: x % 3 != 0 and x % 4 !=0, map(lambda x,y: x+ y, xrange(0, 100), xrange(100,200)))) 6634 |