Python's built-in filter() functions are used to filter the sequence.
and map() similar, filter() also receive a function and a sequence. And the map() difference is that the filter() incoming function acts on each element in turn, and then whether True False the element is persisted or discarded based on the return value.
For example, in a list, delete even numbers, keep only odd numbers, and you can write:
def is_odd (n): return n% 2 = = 1list (filter (is_odd, [1, 2, 4, 5, 6, 9, ten,])# results: [1 , 5, 9, []
To delete an empty string from a sequence, you can write:
def Not_empty (s): return and S.strip () List (filter (Not_empty, ['A'"') 'B ' ' C ' ' ' ])# results: [' A ', ' B ', ' C ']
filter()the key to using this higher-order function is to implement a "filter" function correctly.
Notice that the filter() function returns one, which is Iterator an inert sequence, so to force the result of the filter() calculation, you need to use the list() function to get all the results and return to the list.
# Coding=utf-8 def is_palindrome (n): return str (n) = = str (n) [::-1 = Filter (Is_palindrome, Range (1,))print (list (output))
Small summary, the use of slices [::-1] The reverse sequence of slices, range lists the certificate sequence within the specified range
SortedSorting algorithms
Sorting is also an algorithm that is often used in programs. Whether you use bubble sorting or fast sorting, the core of the sort is to compare the size of the two elements. If it is a number, we can compare it directly, but what if it is a string or two dict? There is no point in directly comparing the size of mathematics, so the process of comparison must be abstracted by functions.
12. Filter