# Python 中的 filter() 方法和 Lambda 函式

Vaibhav Vaibhav 2022年5月17日

## Python 中的 `filter()` 方法和 `lambda` 函式

`filter` 方法是 Python 程式語言中的內建方法，用於從滿足特定條件的迭代中過濾元素。函式表示條件，函式返回 `True` 的值將被考慮在結果中。

`filter()` 接受兩個引數；一個用於過濾的函式，它返回一個布林值和一個可迭代的物件，例如列表或元組。`filter()` 方法是一個迭代器或 `filter` 物件。

`lambda` 函式具有以下語法。

``````lambda < parameters > : < expression >
``````

``````array = [11, 23, 13, 4, 15, 66, 7, 8, 99, 10]
new_array = list(filter(lambda x: x <= 20, array))
print("Old Array:", array)
print("New Array:", new_array)
``````

``````Old Array: [11, 23, 13, 4, 15, 66, 7, 8, 99, 10]
New Array: [11, 13, 4, 15, 7, 8, 10]
``````

### 從整數列表中過濾所有偶數

``````array = [1, 2, 3, 4, 5, 66, 77, 88, 99, 100]
new_array = list(filter(lambda x: x % 2 == 0, array))
print("Old Array:", array)
print("New Array:", new_array)
``````

``````Old Array: [1, 2, 3, 4, 5, 66, 77, 88, 99, 100]
New Array: [2, 4, 66, 88, 100]
``````

### 從整數列表中過濾所有奇數

``````array = [1, 2, 3, 4, 5, 66, 77, 88, 99, 100]
new_array = list(filter(lambda x: x % 2 == 1, array))
print("Old Array:", array)
print("New Array:", new_array)
``````

``````Old Array: [1, 2, 3, 4, 5, 66, 77, 88, 99, 100]
New Array: [1, 3, 5, 77, 99]
``````

### 從字串列表中過濾所有長度為 5 的字串

``````array = [
"hello",
"python",
"world",
"walking",
"sleep",
"shelter",
"food",
]
new_array = list(filter(lambda x: len(x) == 5, array))
print("Old Array:", array)
print("New Array:", new_array)
``````

``````Old Array: ['hello', 'python', 'world', 'walking', 'sleep', 'shelter', 'food']
New Array: ['hello', 'world', 'sleep']
``````

### 從整數列表中過濾 `[10, 20]` 範圍內的所有數字

``````array = [11, 23, 13, 4, 15, 66, 7, 8, 99, 10]
new_array = list(filter(lambda x: 10 <= x <= 20, array))
print("Old Array:", array)
print("New Array:", new_array)
``````

``````Old Array: [11, 23, 13, 4, 15, 66, 7, 8, 99, 10]
New Array: [11, 13, 15, 10]
``````

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.