Python filter() 函式



**Python filter() 函式**允許您根據指定的條件過濾掉可迭代物件中的元素。如果一個物件允許透過迭代檢索其項,則稱該物件是可迭代的,例如列表元組字串

**filter()** 函式將條件應用於可迭代物件的每個元素,並檢查哪個元素滿足給定條件。基於此,它建立一個新的可迭代物件,其中僅包含滿足條件的元素。

**filter()** 是內建函式之一,不需要任何模組。

語法

Python **filter()** 函式的語法如下所示:

filter(function, iterable)

引數

Python **filter()** 函式接受兩個引數:

  • **function** - 它指定一個條件,根據該條件過濾掉可迭代元素。

  • **iterable** - 它表示一個物件,例如列表、字串或元組。

返回值

Python **filter()** 函式返回一個新的可迭代物件。

filter() 函式示例

練習以下示例以瞭解如何在 Python 中使用 **filter()** 函式

示例:filter() 函式的基本用法

以下示例顯示了 Python filter() 函式的基本用法。在這裡,此函式接受一個 lambda 表示式和一個列表物件,以從指定的列表中過濾掉偶數。

numerics = [59, 22, 71, 65, 12, 6, 19, 28, 17, 5]
lstOfevenNums = list(filter(lambda x: (x % 2 == 0), numerics))
print("The list of even numbers from the list:")
print(lstOfevenNums)

當我們執行以上程式時,它會產生以下結果:

The list of even numbers from the list:
[22, 12, 6, 28]

示例:從字串中過濾母音

在下面的程式碼中,我們定義了一個使用者定義函式,該函式將作為引數傳遞給 filter() 函式,以檢查和分離指定字串中的母音。

def checkVowel(chars):
   vowelsLst = 'aeiou'
   return chars in vowelsLst
orgnlStr = "Tutorials Point"
newVowels = ''.join(filter(checkVowel, orgnlStr))
print("The vowels from the given string:")
print(newVowels)

以下是上述程式碼的輸出:

The vowels from the given string:
uoiaoi

示例:從列表中移除假值

如果我們將 None 作為函式引數傳遞,則 filter 函式將移除可迭代物件中所有被認為是假的值。Python 中的一些假值是 ""、0、False 等。以下程式碼說明了這一點:

dataLst = [55, "", None, "Name", "Age", 25, None]
newLst = list(filter(None, dataLst))
print("The new list without None value:")
print(newLst)

上述程式碼的輸出如下:

The new list without None value:
[55, 'Name', 'Age', 25]

示例:從字典中過濾記錄

在下面的程式碼中,建立了一個字典。然後,使用 filter() 函式刪除 id 小於 100 的元素。

employees = [
   {"name": "Ansh", "id": 121},
   {"name": "Vivek", "id": 100},
   {"name": "Tapas", "id": 93}
]
newLst = list(filter(lambda x: (x['id'] >= 100), employees))
print("The new list with id greater than or equal to 100:")
print(newLst)

以下是上述程式碼的輸出:

The new list with id greater than or equal to 100:
[{'name': 'Ansh', 'id': 121}, {'name': 'Vivek', 'id': 100}]
python_built_in_functions.htm
廣告