Every time I use Python, I check how to use higher-order functions (map, filter, reduce), so I'll leave it as a memo.
Also, I recently started studying Python 3, but since the writing style is slightly different between Python 2 and 3, I will write both for comparison.
What is a higher-order function in the first place is a function that takes a function as an argument. For example, it is used when you want to perform some processing on each element of the array.
It is used when you want to process all elements </ font> of the array. In the following example, all the elements of the array are doubled and output.
print map(lambda x: x * 2, range(1, 5))
print (list(map(lambda x: x * 2, range(1, 5))))
[2, 4, 6, 8]
It is used when you want to process only the elements that match the condition </ font> in the array. In the following example, only even numbers are extracted from the elements of the array.
print filter(lambda x: x % 2 == 0, range(1, 5))
print (list(filter(lambda x: x % 2 == 0, range(1, 5))))
Use this when you want to combine multiple elements into one </ font>. Specifically, two elements are extracted from the beginning of the array and processed, and then the result and the next element are processed, and so on.
However, in Python 3, the reduce function has been removed from the core Python functions and can only be used by importing the functools </ font> module.
In the following example, the sum of all the elements of the array is calculated.
print reduce(lambda x, y: x + y, range(1, 5))
import functools print (functools.reduce(lambda x, y: x + y, range(1, 5)))
It's partly because I'm new to Python 3, but my personal impression is that Python 2 is simpler to write ...