Filter read: 265432
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, 10, 15]))# 结果: [1, 5, 9, 15]
To delete an empty string from a sequence, you can write:
def not_empty(s): return s and s.strip()list(filter(not_empty, [‘A‘, ‘‘, ‘B‘, None, ‘C‘, ‘ ‘]))# 结果: [‘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.
Using filter to calculate prime number
One way to calculate prime numbers is through the method of the Fourier sieve, which is very simple to understand:
First, list 2 all the natural numbers from the beginning, constructing a sequence:
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
To take the first number of a sequence 2 , it must be a prime, and then 2 sift away the multiples of the sequence 2 :
3, 4, 5, 6, 7, 8, 9,, one, ten,, 1 8, ...
To take the first number of a new sequence 3 , it must be a prime, and then 3 sift away the multiples of the sequence 3 :
5, 6, 7, 8, 9, Ten, one, A, a, a, (+), +, ...
Take the first number of a new sequence 5 , and then sift away the multiples of the 5 sequence 5 :
7, 8, 9, Ten, one, A, and a , 5>18, ...
Keep sifting down and you can get all the primes.
Using Python to implement this algorithm, you can first construct an 3 odd sequence from the beginning:
def _odd_iter(): n = 1 while True: n = n + 2 yield n
Note that this is a generator and is an infinite sequence.
Then define a filter function:
def _not_divisible(n): return lambda x: x % n > 0
Finally, define a generator that continually returns the next prime number:
def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列
The generator returns the first prime number 2 , and then takes advantage of the filter() new sequence that continuously produces the filter.
Because primes() it is also an infinite sequence, it is called to set a condition for exiting the loop:
# 打印1000以内的素数:for n in primes(): if n < 1000: print(n) else: break
Note that Iterator it is a sequence of lazy computations, so we can use Python to represent the sequence of "all natural numbers", "All primes", and the code is very concise.
Python's Filter