您的位置:首页 > 编程语言 > Python开发

Python特殊语法:filter、map、reduce求和差积、lambda

2017-11-18 15:30 621 查看
https://www.cnblogs.com/longdouhzt/archive/2012/05/19/2508844.html

1、filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回:

root@kali:~/python/laowangpy/function# python
Python 2.7.3 (default, Mar 14 2014, 11:57:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
...     return x%2 == 0#偶数
...
>>> filter(f,range(1,100))#对1-100中取出所有的偶数
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
>>>
>>> def g(x):
...     return x != "a"
...
>>> filter(g,"abdgafr")#过滤字符串a
'bdgfr'
>>>


2、map(function, sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回:

>>> def h(y):
...     return y*y
...
>>> map(h,range(1,10))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>

>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def cube(x) : return x + x
...
>>> map(cube , "abcde")
['aa', 'bb', 'cc', 'dd', 'ee']
另外map也支持多个sequence,这就要求function也支持相应数量的参数输入:
>>> def add(x, y): return x+y
>>> map(add, range(8), range(8))
[0, 2, 4, 6, 8, 10, 12, 14]


3、reduce(function, sequence, starting_value):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和:

>>> def add(x,y): return x + y
>>> reduce(add, range(1, 11))
55 (注:1+2+3+4+5+6+7+8+9+10)
>>> reduce(add, range(1, 11), 20)
75 (注:1+2+3+4+5+6+7+8+9+10+20)


4、lambda:这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数,是从LISP借用来的,可以用在任何需要函数的地方:

>>> g = lambda x: x * 2
>>> g(3)
6
>>> (lambda x: x * 2)(3)
6


Python中,也有几个定义好的全局函数方便使用的,filter, map, reduce。

1 from functools import reduce
2 foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
3
4 print (list(filter(lambda x: x % 3 == 0, foo)))
5 #[18, 9, 24, 12, 27]
6
7 print (list(map(lambda x: x * 2 + 10, foo)))
8 #[14, 46, 28, 54, 44, 58, 26, 34, 64]
9
10 print (reduce(lambda x, y: x + y, foo))
11 #139

求1-100内的偶数
>>> print (list(filter(lambda x: x%2 == 0,range(1,100))))
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
>>>

上面例子中的map的作用,非常简单清晰。但是,Python是否非要使用lambda才能做到这样的简洁程度呢?在对象遍历处理方面,其实Python的for..in..if语法已经很强大,并且在易读上胜过了lambda。   

  比如上面map的例子,可以写成:print ([x * 2 + 10 for x in foo]) 非常的简洁,易懂。   

      filter的例子可以写成:print ([x for x in foo if x % 3 == 0]) 同样也是比lambda的方式更容易理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  filter python map reduce lambda