Python's high-order functions map, reduce, filter

higher order functions

Passing functions as parameters, such functions are called higher-order functions, and higher-order functions are the embodiment of functional programming.

Functional programming refers to this highly abstract programming paradigm

Calculates the absolute value of two values

  • method one
def sum_num(a,b):
	return abs(a)+abs(b)

result = sum_num(1,-1)
  • Method Two
def sum_num(a,b,f):
	return f(a)+f(b)

result = sum_num(-1,2,abs)

The significance of high-order functions is to make the code more concise and reduce code repetition

built-in higher-order functions

map()

def func(x):
    return x * 2


list1 = [1, 2, 3, 4]
result = map(func,list1)
print(result)
print(list(result))

The result is:

<map object at 0x1037f27b8>
[2, 4, 6, 8]

map(func, lst), apply the function variable func to each element of the lst variable, and return an iterator (python2 returns a list), if you want to get a list of results, just convert it into a list format

reduce()

import functools

def func(a,b):
    return a + b

list1 = [1, 2, 3, 4]
result = functools.reduce(func,list1)
print(result)

The result is:

10

reduce(func(x,y), lst), where func must have two parameters.
When using the reduce() function, the leading package is required.
The result of each calculation continues to be cumulatively calculated with the next element of the sequence.
The parameters passed in by reduce() must accept 2 parameters

filter()

def func(x):
    return x % 2 == 0

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = filter(func,list1)
print(result)
print(list(result))

The result is:

<filter object at 0x10fce37b8>
[2, 4, 6, 8]

The filter(fun,lst) function is used to filter sequences, filter out unqualified elements, and return an iterator, if you want a list, you can use list() to convert

Guess you like

Origin blog.csdn.net/qq_41158271/article/details/115314354