Python 函数lambda(), filter(), map(), reduce()
2017-03-21 12:43
1216 查看
1 filter
filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)
比如
def f(x): return x % 2 != 0 and x % 3 != 0
x = filter(f, range(2, 25))
也可以用推导式这样写
x = [x for x in range(2, 25) if x % 2 != 0 and x % 3 != 0 ]
print ( x )
也可以用filter + lambda 这样写
x = filter( lambda x:x % 2 != 0 and x % 3 != 0, range(2, 25))
print ( x )
2 map
map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回,比如
data = map(lambda x: x*x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(data)
输出 [1, 4, 9, 16, 25, 36, 49, 64, 81]
再比如把列表的数字全部转为字符串
data = map(lambda x: str(x), [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(data)
3 reduce
reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
比方说对一个序列求和,就可以用reduce实现
filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)
比如
def f(x): return x % 2 != 0 and x % 3 != 0
x = filter(f, range(2, 25))
也可以用推导式这样写
x = [x for x in range(2, 25) if x % 2 != 0 and x % 3 != 0 ]
print ( x )
也可以用filter + lambda 这样写
x = filter( lambda x:x % 2 != 0 and x % 3 != 0, range(2, 25))
print ( x )
2 map
map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回,比如
data = map(lambda x: x*x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(data)
输出 [1, 4, 9, 16, 25, 36, 49, 64, 81]
再比如把列表的数字全部转为字符串
data = map(lambda x: str(x), [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(data)
3 reduce
reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
比方说对一个序列求和,就可以用reduce实现
>>> def add(x, y): ... return x + y ... >>> reduce(add, [1, 3, 5, 7, 9]) 25
相关文章推荐
- python中的lambda匿名函数以及针对序列的内建函数map、filter和reduce
- python2,3中内建函数map,reduce,filter,sorted配合lambda
- Python高阶函数(Map、Reduce、Filter)和lambda函数一起使用 ,三剑客
- 【python】filter,map,reduce和lambda函数介绍
- Python中特殊函数和表达式 filter,map,reduce,lambda
- Python高级特性: 函数编程 lambda, filter,map,reduce
- python几个重要的函数(lambda,filter,reduce,map,zip)
- 【转】python的内建函数:filter,map,reduce,lambda,sorted等
- python几个重要的函数(lambda,filter,reduce,map,zip) 一、匿名函数lambda lambda argument1,argument2,...argumentN :e
- [Python] 函数lambda(), filter(), map(), reduce()
- [Python] 函数lambda(), filter(), map(), reduce()
- Python中的filter、map、reduce、lambda函数
- [Python] 函数lambda(), filter(), map(), reduce()
- python的lambda表达式 内建函数filter map reduce
- python3 常见函数 map、reduce、filter、lambda、sorted
- Python入门 第四天(函数式编程、map、reduce、filter、排序函数、函数返回函数、闭包、匿名函数lambda)
- python函数lambda(), filter(), map(), reduce()
- python中的函数:filter/map/reduce/lambda
- Python 第三篇(上):python文件基础操作、json模块、lambda、map、filter、reduce和函数位置参数
- python几个特别函数map filter reduce lambda