Usage of the filter function in Python

Mondo Technology Updated on 2024-02-03

The filter function in Python provides just thatFilter the sequence to filter out elements that don't meet the criteria, returning a new list of elements that meet the criteria

The filter function prototype is filter(function or none, iterable) filter object,The first parameter in the list is a functionThe second is a sequence, each element of the sequence is passed as an argument to the function for judgment, then returns true or false, and finally puts the element that returns true into a new list, the filter object.

In simple terms,The filter function is to filter out the elements that match the specified operation from the specified sequence according to the specified operation

The key to using the filter function in Python is thisWhat kind of function should be selected as a parameter?From the point of view of element filtering, this function is of course a function that has a judgment function, that is, a function whose result is true or false, and from this point of view, it can be considered as a class of functions with the same function as an if statement. Here's an example:

The example shows how to filter odd and square numbers from a sequence, which is the basic usage of the filter function in Python, and a more complex way to use it is to pass a more complex function in the first parameter, such as a human recognition function, to filter out a new group of people with the same facial features from a group of people.

Related Pages