Python filter() 函數

Python 內置函數 Python 內置函數


描述

filter() 函數用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。

該接收兩個參數,第一個為函數,第二個為序列,序列的每個元素作為參數傳遞給函數進行判斷,然後返回 True 或 False,最後將返回 True 的元素放到新列表中。

注意: Pyhton2.7 返回列表,Python3.x 返回迭代器對象,具體內容可以查看:Python3 filter() 函數

語法

以下是 filter() 方法的語法:

filter(function, iterable)

參數

  • function -- 判斷函數。
  • iterable -- 可迭代對象。

返回值

返回列表。


實例

以下展示了使用 filter 函數的實例:

過濾出列表中的所有奇數:

#!/usr/bin/python # -*- coding: UTF-8 -*- def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(newlist)

輸出結果 :

[1, 3, 5, 7, 9]

過濾出1~100中平方根是整數的數:

#!/usr/bin/python # -*- coding: UTF-8 -*- import math def is_sqr(x): return math.sqrt(x) % 1 == 0 newlist = filter(is_sqr, range(1, 101)) print(newlist)

輸出結果 :

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Python 內置函數 Python 內置函數