• Index

### 关于作者

#### filter

Python内建的`filter()`函数用于过滤序列。

`map()`类似，`filter()`也接收一个函数和一个序列。和`map()`不同的是，`filter()`把传入的函数依次作用于每个元素，然后根据返回值是`True`还是`False`决定保留还是丢弃该元素。

``````def is_odd(n):
return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
``````

``````def not_empty(s):
return s and s.strip()

list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))
# 结果: ['A', 'B', 'C']
``````

### 用filter求素数

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

``````def _odd_iter():
n = 1
while True:
n = n + 2
yield n
``````

``````def _not_divisible(n):
return lambda x: x % n > 0
``````

``````def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一个数
yield n
it = filter(_not_divisible(n), it) # 构造新序列
``````

``````# 打印1000以内的素数:
for n in primes():
if n < 1000:
print(n)
else:
break
``````

### 练习

```# -*- coding: utf-8 -*-

def is_palindrome(n):
----
pass
----
# 测试:
output = filter(is_palindrome, range(1, 1000))
print(list(output))
```

### 小结

`filter()`的作用是从一个序列中筛出符合条件的元素。由于`filter()`使用了惰性计算，所以只有在取`filter()`结果的时候，才会真正筛选并每次返回下一个筛出的元素。

do_filter.py

prime_numbers.py