## Summary of map, filter and reduce in Python

sxxbxh 2020-11-14 13:27:38
summary map filter reduce python

stay Python We often encounter the need to use map、filter and reduce Three functions , Do you know when to use them ? Let's learn and understand one by one Python in map、filter and reduce Use , Let's see !

1、map function

map The specification of a function is , take ⼀ Functions are mapped to ⼀ A loss ⼊ On all the elements of the list .

map(function_to_apply, list_of_inputs)

⼤ Most of the time , We're going to put all the elements in the list ⼀ Pass it on to ⼀ A function , And collect the output . such as ：

items = [1, 2, 3, 4, 5]

squared = []

for i in items:

squared.append(i**2)

and Map Functions let us ⽤⼀ Simple ⽽ Much more beautiful ⽅ To achieve , as follows ：

items = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, items))

⼤ Most of the time , We make ⽤ Anonymous functions lambdas To match map function , Not only ⽤ On ⼀ Input of list ⼊, We are very much ⾄ Sure ⽤ On ⼀ Function of list !

def multiply(x):

return (x*x)

return (x+x)

funcs = [multiply, add]

for i in range(5):

value = map(lambda x: x(i), funcs)

print(list(value))

# Output:

# [0, 0]

# [1, 2]

# [4, 4]

# [9, 6]

# [16, 8]

2、Filter function

Filter Functions are easy to understand , Namely filter Filter the elements in the list , And back to ⼀ A list of all elements that meet the requirements , If the function is mapped to the element, the return value is True. Here's a simple example to help you understand ：

number_list = range(-5, 5)

less_than_zero = filter(lambda x: x < 0, number_list)

print(list(less_than_zero))

# Output: [-5, -4, -3, -2, -1]

This filter Be similar to ⼀ individual for loop , But it is ⼀ Built in functions , And faster .

3、Reduce function

When need is right ⼀ List in ⾏⼀ When calculating and returning the results ,Reduce It's a ⾮ There is often ⽤ Function of . For example ⼦, When you need to calculate ⼀ When the product of a list of integers . Usually in Python You may be able to ⽤ Basic for Loop to complete the task . Now let's try reduce：

from functools import reduce

product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )

# Output: 24

Python in map、filter and reduce This is the summary of the use of , Do you master the essence? ? in general ,map、filter and reduce Three functions for functional programming , It is extremely convenient and fast , It is recommended that everyone try to use it more , A new continent is sure to be found ! Zhengzhou Tongji infertility hospital :http://jbk.39.net/yiyuanzaixian/zztjyy/ Zhengzhou male gynecology hospital online consultation :http://news.39.net/ylzx/zztjyy/ Zhengzhou gynecological hospital where good :http://jbk.39.net/yiyuanzaixian/sysdfkyy/