Python中的map、reduce和filter函數(shù)是如何工作的?
在Python中,map、reduce和filter都是非常實用的函數(shù)。愛掏網(wǎng) - it200.com它們可以讓我們更方便地對序列進行操作,提高我們的程序效率。愛掏網(wǎng) - it200.com那么這些函數(shù)是如何工作的呢?本文將為你詳細介紹。愛掏網(wǎng) - it200.com
map()
函數(shù)是Python中的內(nèi)置函數(shù),它能夠根據(jù)提供的函數(shù)對序列進行映射,返回一個新的列表。愛掏網(wǎng) - it200.com它的基本語法為:
map(function, iterable, ...)
其中,function
是一個函數(shù),iterable
是一個可迭代對象。愛掏網(wǎng) - it200.com我們也可以將iterable
進行擴展,包括多個其他的迭代器。愛掏網(wǎng) - it200.com例如:
map(function, iterable1, iterable2, ...)
下面是一個簡單的例子,將一個列表中的所有元素乘以2:
def double(x):
return x * 2
lst = [1, 2, 3, 4, 5]
new_lst = map(double, lst)
print(list(new_lst)) # [2, 4, 6, 8, 10]
這個例子中,我們定義了一個函數(shù)double(x)
,將x
乘以2,然后通過map()
函數(shù)將這個函數(shù)應(yīng)用到lst
中的所有元素上,最后返回一個新的列表。愛掏網(wǎng) - it200.com
我們也可以通過lambda
表達式來實現(xiàn)這個功能:
lst = [1, 2, 3, 4, 5]
new_lst = map(lambda x: x * 2, lst)
print(list(new_lst)) # [2, 4, 6, 8, 10]
這里的lambda
表達式等價于上面的double(x)
函數(shù)。愛掏網(wǎng) - it200.com
2. reduce函數(shù)
reduce()
函數(shù)也是Python中的內(nèi)置函數(shù),它能夠?qū)⒁粋€函數(shù)作用在一個序列上,將序列中的前兩個元素進行操作,得到一個結(jié)果后再與第三個元素進行操作,直到序列中的所有元素都完成操作。愛掏網(wǎng) - it200.com它的基本語法為:
reduce(function, iterable[, initial])
其中,function
是一個函數(shù),iterable
是一個可迭代對象,initial
是一個可選項,表示操作的初始值。愛掏網(wǎng) - it200.com
下面是一個例子,計算列表中所有元素的乘積:
from functools import reduce
lst = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, lst)
print(product) # 120
這里我們需要使用functools
模塊中的reduce()
函數(shù)。愛掏網(wǎng) - it200.com在這個例子中,我們使用了lambda
表達式來定義對兩個元素的操作(將它們相乘),然后將這個表達式傳遞給reduce()
函數(shù)。愛掏網(wǎng) - it200.com最后,整個序列的元素被逐個乘起來,得到結(jié)果為120。愛掏網(wǎng) - it200.com如果沒有提供initial
參數(shù),reduce()
函數(shù)將從序列的第一個元素開始操作。愛掏網(wǎng) - it200.com
3. filter函數(shù)
filter()
函數(shù)也是Python中的內(nèi)置函數(shù),它能夠根據(jù)給定的函數(shù)對序列進行過濾,返回一個新的列表,這個列表包含所有在序列中返回True
的元素。愛掏網(wǎng) - it200.com它的基本語法為:
filter(function, iterable)
其中,function
是一個函數(shù),iterable
是一個可迭代對象,表示要進行過濾的序列。愛掏網(wǎng) - it200.com
下面是一個例子,從一個列表中篩選出所有的偶數(shù):
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_lst = filter(lambda x: x % 2 == 0, lst)
print(list(even_lst)) # [2, 4, 6, 8, 10]
我們同樣可以使用一個函數(shù)來代替lambda
表達式: