Python3 filter() 函數

Python3 內置函數 Python3 內置函數


描述

filter() 函數用於過濾序列,過濾掉不符合條件的元素,返回一個迭代器對象,如果要轉換為列表,可以使用 list() 來轉換。

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

語法

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

filter(function, iterable)

參數

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

返回值

返回一個迭代器對象


實例

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

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

#!/usr/bin/python3 def is_odd(n): return n % 2 == 1 tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) newlist = list(tmplist) print(newlist)

輸出結果 :

[1, 3, 5, 7, 9]

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

#!/usr/bin/python3 import math def is_sqr(x): return math.sqrt(x) % 1 == 0 tmplist = filter(is_sqr, range(1, 101)) newlist = list(tmplist) print(newlist)

輸出結果 :

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

Python3 內置函數 Python3 內置函數