【每天1分钟】PYTHON基础之函数(高阶函数)

【每天1分钟】PYTHON基础之函数(高阶函数)

1. 什么是高阶函数

高阶函数:一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归),满足其一则为高阶函数。

参数为函数

>>> def bar():
	print('in the bar......')

	
>>> def foo(func):
	func()
	print('in the foo......')

	
>>> foo(bar)
in the bar......
in the foo......
>>> 

返回值为函数

>>> def bar():
	print('in the bar......')

	
>>> def foo(func):
	print('in the foo......')
	return func

>>> foo(bar)
in the foo......
<function bar at 0x000001E66B373840>
>>> res = foo(bar)
in the foo......
>>> res()
in the bar......
>>> 

2. 高阶函数

2.1 map

map函数

>>> num = [1, 2, 3, 4, 5]
>>> def square(x):
	return x ** 2

# 模拟 map 函数
>>> def map_test(func, iter):
	num_1 = []
	for i in iter:
		ret = func(i)
		num_1.append(ret)
	return num_1.__iter__()

# map_test函数
>>> print(list(map_test(square, num)))
[1, 4, 9, 16, 25]
>>> 
# map函数
>>> print(list(map(square, num)))
[1, 4, 9, 16, 25]

# #当然map函数的参数1也可以是匿名函数、参数2也可以是字符串
>>> print(list(map_test(lambda x:x.upper(),"amanda")))
['A', 'M', 'A', 'N', 'D', 'A']
>>> print(list(map(lambda x:x.upper(),"amanda")))
['A', 'M', 'A', 'N', 'D', 'A']
>>> 

2.2 filter

filter函数

>>> names=["Alex","amanda","xiaowu"]
>>> #filter函数机制
>>> def filter_test(func,iter):
	names_1=[]
	for i in iter:
		if func(i): #传入的func函数其结果必须为bool值,才有意义
			names_1.append(i)
	return names_1

>>> #filter_test函数
>>> print(filter_test(lambda x:x.islower(),names))
['amanda', 'xiaowu']
>>> #filter函数
>>> print(list(filter(lambda x:x.islower(),names)))
['amanda', 'xiaowu']
>>> 

2.3 reduce

reduce函数

>>> #reduce函数不是内置函数,而是在模块functools中的函数,故需要导入
>>> from functools import reduce
>>> nums=[1,2,3,4,5,6]
>>> #reduce函数的机制
>>> def reduce_test(func,array,ini=None): #ini作为基数
	if ini == None:
		ret =array.pop(0)
	else:
		ret=ini
	for i in array:
		ret=func(ret,i)
	return ret

>>> #reduce_test函数,叠乘
>>> print(reduce_test(lambda x,y:x*y,nums,100))
72000
>>> #reduce函数,叠乘
>>> print(reduce(lambda x,y:x*y,nums,100))
72000
>>> help(reduce)
Help on built-in function reduce in module _functools:

reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    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.

>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值