Python 高阶函数

高阶函数: map reduce sorted filter zip

1.map(func, *iterables) --> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

map(func, *iterables)

参数:

function :函数

*iterables :一个或多个可迭代对象

返回值:map object

功能: 制作一个迭代器(可迭代对象),通过使用函数,需要传入的参数来自每一个可迭代对象

什么时候停止:当最短的可迭代对象被耗尽的时候停止

注意:定义函数时,需要注意有多少个可迭代对象,就有多个参数

list_data = [1, 2, 3]
list_data1 = [4, 5, 6, 7]
list_data2 = [8, 9, 10, 11, 12]

def computes_func(x, y, z):
    return x + y + z

map_obj = map(computes_func, list_data, list_data1, list_data2)
print(map_obj, type(map_obj))
print(list(map_obj))

2.reduce 迁入到其他模块(functools)了,需要引入

reduce(function, sequence, initial=_initial_missing):

参数:

function: 函数

sequence:序列

initial:初始化

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

=> ((((1+2)+3)+4)+5)

=> x = 1, y = 2 =>3

=> x = 3, y = 3 =>6

=> x = 6, y = 4 =>10

=> x = 10,y = 5 =>15

For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5).

If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

from functools import reduce

data = reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
print(data, type(data))

3.sorted:排序 和sort的区别:

list中的sort的方法,所以他依赖list

sorted(iterable, /, *, key=None, reverse=False)

他不依赖与list,所以他排序的返回值比较广:对iterable进行排序

sort(self, /, *, key=None, reverse=False)

只针对列表进行排序,但是两个在排序上相似,只是调用方式不同

list.sort(): 在原列表进行排序

sorted():新建一个列表进行排序

list_data = [5, 2, 7, 2, 1, 9, 4, 3]
sorted(list_data)
list_data.sort()

4,filter:过滤

filter(function or None, iterable)

参数: function 偶然None :函数或参数为空

iterable:可迭代对象(一个)

返回值: filter object

功能:过滤 => 肯定有过滤的条件

list_data = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def filter_func(x):
    if x % 2 !=0:
        return True

filter_obj = filter(filter_func, list_data)
print(filter_obj, type(filter_obj))
print(list(filter_obj))

5.zip() :压缩

A zip object yielding tuples until an input is exhausted.

参数:*iterables:一个或多个可迭代对象

返回值:zip object 功能:从你传入多个可迭代对象,从每一个可迭代对象中取元素

第一次去取所有可迭代对象的第一个元素

第二次去取所有可迭代中的第二个元素 、、、

什么时候结束:最短的被耗尽了

三个元组,每个元组有三个元素

data = zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
print(data)
print(list(data))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值