PYTHON Practice Day 1

PYTHON Practice Day 1

Higher order function

map function (compared to the use of the FOR loop, MAP does not occupy too much memory, FOR needs to be calculated through each loop, but MAP is directly used for multiple calculations)

When there is more than one seq, map can perform the process shown in the following figure on each seq in parallel (note that it is parallel):
As can be seen from the figure, after each element at the same position of seq is passed into a multiple func function at the same time, a return value is obtained and the return value is stored in a list.  Let's look at an example with multiple seq:

As can be seen from the figure, after each element at the same position of seq is passed into a multiple func function at the same time, a return value is obtained and the return value is stored in a list. Let's look at an example with multiple seq:

 print map(lambda x , y : x ** y, [2,4,6],[3,2,1])
>>>[8, 16, 6]

map (function, iterable)
function-function
iterable-one or more sequences

// 
def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]

reduce function
reduce (reduce(function, iterable[, initializer])
function – function, with two parameters
iterable – iterable object
initializer – optional, initial parameters

from functools import reduce
def reduce1(x,y):
	return x+y
s = reduce(reduce1,[1,2,3,4,5]
>>>print(s)
>>>15

Guess you like

Origin blog.csdn.net/weixin_49712647/article/details/112366423