# Python `filter()`函數
> 原文: [https://thepythonguru.com/python-builtin-functions/filter/](https://thepythonguru.com/python-builtin-functions/filter/)
* * *
于 2020 年 1 月 7 日更新
* * *
`filter()`函數將一個函數和一個序列作為參數并返回一個可迭代的對象,僅按順序產生要為其返回`True`的項目。 如果傳遞了`None`而不是函數,則將求值為`False`的序列中的所有項目刪除。 `filter()`的語法如下:
**語法**: `filter(function or None, iterable) --> filter object`
這是一個例子:
**Python 3**
```py
>>>
>>> def is_even(x):
... if x % 2 == 0:
... return True
... else:
... return False
...
>>>
>>> f = filter(is_even, [1, 3, 10, 45, 6, 50])
>>>
>>> f
<filter object at 0x7fcd88d54eb8>
>>>
>>>
>>> for i in f:
... print(i)
...
10
6
50
>>>
```
試試看:
```py
def is_even(x):
if x % 2 == 0:
return True
else:
return False
f = filter(is_even, [1, 3, 10, 45, 6, 50])
print(f)
for i in f:
print(i)
```
要立即產生結果,我們可以使用`list()`函數。
**Python 3**
```py
>>>
>>> list(filter(is_even, [1, 3, 10, 45, 6, 50]))
[10, 6, 50]
>>>
>>>
>>> list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) # function argument is None
[1, 45, 6, 50]
>>>
```
試一試:
```py
def is_even(x):
if x % 2 == 0:
return True
else:
return False
print( list(filter(is_even, [1, 3, 10, 45, 6, 50])) )
# function argument is None
print( list(filter(None, [1, 45, "", 6, 50, 0, {}, False])) )
```
在 Python 2 中,`filter()`返回實際列表(這不是處理大數據的有效方法),因此您無需將`filter()`包裝在`list()`調用中。
**Python 2**
```py
>>>
>>> filter(is_even, [1, 3, 10, 45, 6, 50])
[10, 6, 50]
>>>
```
這是其他一些例子。
**Python 3**
```py
>>>
>>> filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50]) # lambda is used in place of a function
[1, 3, 45]
>>>
>>>
>>> list(filter(bool, [10, "", "py"]))
[10, 'py']
>>>
>>>
>>> import os
>>>
>>> # display all files in the current directory (except the hidden ones)
>>> list(filter(lambda x: x.startswith(".") != True, os.listdir(".") ))
['Documents', 'Downloads', 'Desktop', 'Pictures', 'bin', 'opt', 'Templates', 'Public', 'Videos', 'Music']
>>>
```
試一試:
```py
# lambda is used in place of a function
print(filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50]))
print(list(filter(bool, [10, "", "py"])))
import os
# display all files in the current directory (except the hidden ones)
print(list(filter(lambda x: x.startswith(".") != True, os.listdir(".") )) )
```
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象