SoFunction
Updated on 2024-11-13

Example analysis of python higher-order functions map and reduce

1, map () passed in two parameters, function and iterable objects (Itreable), map () is to pass in the function of each element of the sequence in turn, the result is the return of a new iterable object (Iterable).

The map() code is as follows:

# Define the f function that returns x*x
def f(x):
  return x*x
# Call map() and act on each element in turn, based on the function and list passed in
s=map(f,[1,2,3,4,5])
# Print the value of the returned iterator
print(list(s))
# View type
print(type(s))

Results:

[1, 4, 9, 16, 25]
<class 'map'>

Process finished with exit code 0

Of course, you can also not use map(), the code is as follows:

# Define a list
l=[1,2,3,4,5]
#() is used to create a list, the result returns the square of the elements of list l in turn, return list
s=[i*i for i in l]
# Print list s
print(s)
# [] is used to create a generator that returns the squares of the elements of list l in order, returning generator
s1=(i*i for i in l)
# Print the values of the elements of generator as a list
print(list(s1))
# View the type of s1
print(type(s1))

Results:

[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
<class 'generator'>

Process finished with exit code 0

This is the whole content of this article, I hope it will help you to learn more.