Python高阶函数:map,filter,reduce和sorted

1、map

语法: map(function, iterable, …)
function – 函数
iterable – 一个或多个序列

map函数,给定一个可迭代的对象,通过map()的作用,转成新的符合要求的对象
Python3.x中map最终的返回值是可迭代对象,最后要进行类型转换

实例:
1、求列表各个数据的平方
Python高阶函数:map,filter,reduce和sorted
2、配合lambda使用
也可以通过lambda代替map中的第一个参数,变为匿名函数形式
Python高阶函数:map,filter,reduce和sorted
3、 提供了两个列表,对相同位置的列表数据进行相加
Python高阶函数:map,filter,reduce和sorted

2、filter

语法:filter(function, iterable)
function – 判断函数。
iterable – 可迭代对象。

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

实例:
1、列出列表中的所有偶数
Python高阶函数:map,filter,reduce和sorted
2、提取纯数字
Python高阶函数:map,filter,reduce和sorted
3、找到列表中年龄大于20的元组
Python高阶函数:map,filter,reduce和sorted
或者使用列表生成式
Python高阶函数:map,filter,reduce和sorted
对于字典来说可以使用字典生成式来找到满足条件的数据
Python高阶函数:map,filter,reduce和sorted

3、reduce

Python3.x中需要在functools包中导入reduce

语法:
reduce(function, iterable[, initializer])
function – 函数,有两个参数
iterable – 可迭代对象
initializer – 可选,初始参数

reduce() 函数会对参数序列中元素进行累积。
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果

实例:
Python高阶函数:map,filter,reduce和sorted
Python高阶函数:map,filter,reduce和sorted

4、sorted

注意区别sorted和sort函数:
sorted(list) 返回排序后的列表,原列表不变
list.sort()原列表变成排序后的列表,返回值为null
Python高阶函数:map,filter,reduce和sortedPython高阶函数:map,filter,reduce和sorted

语法:
sorted(iterable, key=None, reverse=False)
iterable – 可迭代对象。
key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

Python高阶函数:map,filter,reduce和sorted
Python高阶函数:map,filter,reduce和sorted