Python中的Map, Filter和Reduce
2017-06-27 16:54
531 查看
Map
Map会对一个输入列表中的所有元素做一个函数操作.map(function_to_apply, input_list)
例子:
input_list = [1,2,3,4,5] doubled = list(map(lambda x: 2*x, input_list))
操作就是把一个列表中的所有元素乘以2, 相当于:
input_list = [1,2,3,4,5] doubled = [] for i in input_list: doubled.append(i*2)
这个可以被推导式所取代, 比如取代上面的代码使用:
input_list = [1,2,3,4,5] doubled = [i*2 for i in input_list]
Filter
filter用来过滤列表中的元素, 并且返回一个由所有符合要求的元素所构成的列表.例子:
numbers = range(-10, 10) less_than_3 = filter(lambda x: x<0, numbers)
这个也可以被推导式所取代:
numbers = range(-10, 10) less_than_3 = [i for i in numbers if i<3]
Reduce
Reduce可以对一个列表进行一些计算, 并且返回一个结果. 比如计算一个整数列表的乘积. 如果不使用Reduce则会需要一个for循环来解决, 使用Reduce会方便很多.例子:
numbers = [1,2,3,4,5,6] product = reduce((lambda x, y: x*y), numbers)
如果不适用reduce, 会需要一个for循环:
numbers = [1,2,3,4,5,6] product = 1 for i in numbers: product *= i
相关文章推荐
- python 内建函数filter() ,map(),reduce()
- python的几个内建函数:apply(),filter(),map(),reduce()
- Python特殊语法:filter、map、reduce、lambda [转]
- Python 特殊语法filter、map、reduce、lambda
- python内置函数map/reduce/filter
- Python特殊语法:filter、map、reduce、lambda [转]
- python 中的filter, map, reduce方法解释
- Python内建函数之——filter,map,reduce
- Python特殊语法:filter、map、reduce、lambda
- python的几个内建函数:apply(),filter(),map(),reduce()
- python 的几个内置函数(lambda ,zip, filter, map, reduce )用法
- python中的map,filter,reduce,lambda (转)
- Python中几个操作列表的内置函数filter(),map(),reduce(),lambda
- python的几个内建函数:apply,filter,map,reduce
- python的几个内建函数:apply(),filter(),map(),reduce()
- python中的map,filter,reduce,lambda (转)
- python几个内置函数之-filter,map,reduce
- python filter, map, 和reduce
- python:map filter reduce
- Python特殊语法:filter、map、reduce、lambda、yield