python——高阶函数——map reduce filter sorted
2017-04-18 23:13
651 查看
map
def double(a): return 2 * a def upper(str): return str.upper() print map(double, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print map(upper, 'martin')
output:
[2, 4, 6, 8, 10, 12, 14, 16, 18] ['M', 'A', 'R', 'T', 'I', 'N']
总结:
map第一个参数为函数(1个参数),第二个参数为list
map功能把函数作用于list每个元素,返回新list
reduce
def add(a, b): return a + b def mul(a, b): return a * b print reduce(add, [1, 3 ,5 ,7, 9]) print reduce(mul, [1, 3 ,5 ,7, 9])
output:
25 945
总结:
reduct第一个参数为函数(2个参数),第二个参数为list
reduct功能使用函数作累积计算
filter
def odd(n): return n % 2 == 1 def prime(n): if n == 1: return False for i in range(2, n): if n % i == 0: return False return True print filter(odd, range(1, 21)) print filter(prime, range(1, 21))
output:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19] [2, 3, 5, 7, 11, 13, 17, 19]
总结:
filter第一个参数为函数(1个参数,返回布尔值),第二个参数为list
fliter功能根据函数返回结果过滤元素
sorted
def asc(x, y): if x > y: return 1 if x < y: return -1 return 0 def desc(x, y): if x > y: return -1 if x < y: return 1 return 0 print sorted([8, 5, 58, 18, 15]) print sorted([8, 5, 58, 18, 15], asc) print sorted([8, 5, 58, 18, 15], desc)
output:
[5, 8, 15, 18, 58] [5, 8, 15, 18, 58] [58, 18, 15, 8, 5]
总结:
sorted第一个参数为list,第二个参数为函数(2个参数,返回比较结果,通常规定1表示大于,-1表示小于,0表示等于)
sorted功能根据函数比较结果进行排序
注:如果第二个参数omit,直接把>或<或==运算符作用于list元素(如果list元素类型不支持>或<或==,则throw exception)
相关文章推荐
- Python 函数式编程--高阶函数Map、Reduce、Filter、Sorted
- python 高阶函数 map reduce filter sorted 闭包 装饰器
- Python3中的高阶函数(map,reduce,filter,sorted)
- Python学习2--高阶函数map、reduce、filter、sorted
- Python高阶函数——map/reduce/filter/sorted
- python学习(9)高阶函数map、reduce、filter、sorted
- Python进阶:函数式编程(高阶函数,map,reduce,filter,sorted,返回函数,匿名函数,偏函数)...啊啊啊
- python--函数式编程 (高阶函数(map , reduce ,filter,sorted),匿名函数(lambda))
- Python教程学习简记8--Python 高阶函数 map/reduce filter sorted
- Python学习(八)——map、reduce、filter、sorted
- Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数
- 不得不知的python高阶函数(Map、Reduce、Filter)
- python基础之map/reduce/filter/sorted
- python:内建函数、range()、map()、filter()、reduce()、sorted()、集合的使用、functools中的函数使用、MD5加密
- 【转】python的内建函数:filter,map,reduce,lambda,sorted等
- python2,3中内建函数map,reduce,filter,sorted配合lambda
- Java 高阶函数的简单使用:map,reduce,filter,sorted
- Python高阶函数:filter、map、reduce、lambda
- python学习笔记,map/reduce,filter,sorted
- Python 函数式编程(高阶函数、把函数作为参数、map()函数、reduce()函数、filter()函数、自定义排序函数、函数返回函数、闭包、匿名函数、装饰器decorator)