不要在 Python 中使用循環,這些方法其實更棒!
我們知道在 Python 中使用循環速度是很慢,如果你正在處理類似的情況,那該怎么辦呢?
在本文中,我將給大家分享可用于替代 Python 循環的方法和案例:
- Map
- Filter
- Reduce
在開始使用上述函數之前,如果你還不熟悉 lambda 函數,讓我們快速了解一下。
Lambda 函數是常規函數的替代方法。它可以在一行代碼中定義,因此在我們的代碼中占用更少的時間和空間。例如,在下面的代碼中,我們可以看到 lambda 函數的作用。
def multiply_by_2(x):
x*2
lambda 函數
lambda x: x*2
注意:最好使用 lambda 函數而不是常規函數。
1、Map
使用 map 函數,我們可以將函數應用于可迭代對象(列表、元組等)的每個值。
map(function, iterable)
假設我們想在一個列表(可迭代對象)中得到一個正方形的數字。我們將首先創建一個 square() 函數來查找數字的平方。
def square(x):
return x*x
然后,我們將使用 map 函數將 square() 函數應用于輸入數字列表。
input_list = [2, 3, 4, 5, 6]
# Without lambda
result = map(square, input_list)
# Using lambda function
result = map(lambda x: x*x, input_list)
# converting the numbers into a list
list(result)
# Output: [4, 9, 16, 25, 36]
2、Filter
直觀地說,filter 函數用于從可迭代對象(列表、元組、集合等)中過濾掉值。過濾條件在作為參數傳遞給過濾器函數的函數內設置。
filter(function, iterable)
我們將使用 filter 函數來過濾小于 10 的值。
def less_than_10(x):
if x < 10:
return x
然后,我們將使用 Filter 函數將 less_than_10() 函數應用于值列表。
input_list = [2, 3, 4, 5, 10, 12, 14]
# Without lambda
list(filter(less_than_10, input_list))
# using lambda function
list(filter(lambda x: x < 10, input_list))
# Output: [2, 3, 4, 5]
3、Reduce
Reduce 函數與 map 和 filter 函數有點不同。它迭代地應用于可迭代對象的所有值,并且只返回一個值。
在下面的示例中,通過應用加法函數來減少數字列表。最終輸出將是列表中所有數字的總和,即 15。讓我們創建一個添加兩個輸入數字的addition() 函數。
def addition(x,y):
return x + y
接下來,為了獲得列表中所有數字的總和,我們將把這個加法函數作為參數應用到 reduce 函數。
from functools import reduce
input_list = [1, 2, 3, 4, 5]
# Without Lambda function
reduce(addition, input_list))
# With Lambda function
reduce(lambda x,y: x+y, input_list))
# Output: 15