python的 filter, map, reduce, lambda, list comprehension
2017-09-18 11:55
507 查看
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] >>> >>> print(filter(lambda x: x % 3 == 0, foo)) [18, 9, 24, 12, 27] >>> >>> print(map(lambda x: x * 2 + 10, foo)) [14, 46, 28, 54, 44, 58, 26, 34, 64] >>> >>> print(reduce(lambda x, y: x + y, foo)) 139
上面的map和filter都可以用列表推导改写
print(filter(lambda x: x % 3 == 0, foo)) 等价于 print([x for x in foo if x % 3 == 0]) print(map(lambda x: x * 2 + 10, foo)) 等价于 print([x * 2 + 10 for x in foo])
求2到49范围内的素数
>>> nums = range(2, 50) >>> for i in range(2, 8): nums = [x for x in nums if x==i or x % i != 0] >>> nums [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
相关文章推荐
- Python特殊语法:filter、map、reduce、lambda
- Python特殊语法:filter、map、reduce、lambda
- Python特殊语法:filter、map、reduce、lambda [转]
- python常用函数之lambda、reduce、map、sorted、filter
- Python特殊语法:filter、map、reduce、lambda、yield
- Python特殊语法:filter、map、reduce、lambda [转]
- Python中特殊函数和表达式 filter,map,reduce,lambda
- Python特殊语法:filter、map、reduce、lambda
- Python特殊语法:filter、map、reduce、lambda [转]
- Python特殊语法:filter、map、reduce、lambda
- Python特殊语法:filter、map、reduce、lambda
- 转 python 的几个内置函数(lambda ,zip, filter, map, reduce )用法
- Python特殊语法:filter、map、reduce、lambda [转]
- Python特殊语法:filter、map、reduce、lambda [转]
- python中的lambda匿名函数以及针对序列的内建函数map、filter和reduce
- Python中filter、map、reduce、lambda 的用法
- Python特殊语法:filter、map、reduce、lambda [转]
- [Python] 函数lambda(), filter(), map(), reduce()
- python高阶函数之lambda,map,reduce,filter
- Python之filter、map、reduce、lambda