filter是什麼

來源:時尚少女範 2.56W
filter是什麼

filter是一個函式,它用於過濾序列(如列表、元組、集合等)中的元素,並返回滿足指定條件的元素。filter函式接受兩個引數:一個是函式,一個是序列。函式參數是一個判斷條件的函式,用於對序列中的每個元素進行判斷。序列引數是待過濾的序列。filter函式返回一個迭代器,其中包含滿足條件的元素。

具體來說,filter函式會遍歷序列中的每個元素,然後將元素傳入函式進行判斷。如果函式返回True,則將該元素保留;如果函式返回False,則將該元素過濾掉。最終,filter函式返回的迭代器中只包含滿足條件的元素。

示例程式碼:
```
def is_even(num):
return num % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers)

for num in even_numbers:
print(num)
```
輸出結果為:
```
2
4
6
8
10
```

上述程式碼中,is_even函式用於判斷一個數是否為偶數。filter函式根據is_even函式的判斷結果,過濾出序列numbers中的偶數,並將它們放入一個迭代器even_numbers中。最後,通過迴圈遍歷even_numbers,並列印出所有的偶數。

熱門標籤