Python中reduce函數(shù)詳解
reduce函數(shù)原本在python2中也是個內(nèi)置函數(shù),不過在python3中被移到functools模塊中。
reduce函數(shù)先從列表(或序列)中取出2個元素執(zhí)行指定函數(shù),并將輸出結(jié)果與第3個元素傳入函數(shù),輸出結(jié)果再與第4個元素傳入函數(shù),…,以此類推,直到列表每個元素都取完。
1 reduce用法
對列表元素求和,如果不用reduce,我們一般常用的方法是for循環(huán):
def sum_func(arr): ? ? if len(arr) <= 0: ? ? ? ? return 0 ? ? else: ? ? ? ? out = arr[0] ? ? ? ? for v in arr[1:]: ? ? ? ? ? ? out += v ? ? ? ? return out a = [1, 2, 3, 4, 5] print(sum_func(a))
可以看到,代碼量比較多,不夠優(yōu)雅。如果使用reduce,那么代碼將非常簡潔:
from functools import reduce a = [1, 2, 3, 4, 5] def add(x, y): return x + y print(reduce(add, a))
輸出結(jié)果為:
15
2 reduce與for循環(huán)性能對比
與內(nèi)置函數(shù)map和filter不一樣的是,在性能方面,reduce相比較for循環(huán)來說沒有優(yōu)勢,甚至在實際測試中
reduce比for循環(huán)更慢。
from functools import reduce
import time
def test_for(arr):
? ? if len(arr) <= 0:
? ? ? ? return 0
? ? out = arr[0]
? ? for i in arr[1:]:
? ? ? ? out += i
? ? return out
def test_reduce(arr):
? ? out = reduce(lambda x, y: x + y, arr)
? ? return out
a = [i for i in range(100000)]
t1 = time.perf_counter()
test_for(a)
t2 = time.perf_counter()
test_reduce(a)
t3 = time.perf_counter()
print('for循環(huán)耗時:', (t2 - t1))
print('reduce耗時:', (t3 - t2))輸出結(jié)果如下:
for循環(huán)耗時: 0.009323899999999996
reduce耗時: 0.018477400000000005
因此,如果對性能要求苛刻,建議不用reduce, 如果希望代碼更優(yōu)雅而不在意耗時,可以用reduce。
到此這篇關(guān)于Python中reduce函數(shù)詳解的文章就介紹到這了,更多相關(guān)Python reduce函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?BeautifulSoup4實現(xiàn)數(shù)據(jù)解析與提取
Beautiful?Soup是一個Python的庫,用于解析HTML和XML文檔,提供了方便的數(shù)據(jù)提取和操作功能,下面小編就來和大家詳細(xì)聊聊如何利用BeautifulSoup4實現(xiàn)數(shù)據(jù)解析與提取吧2023-10-10
Python可變參數(shù)會自動填充前面的默認(rèn)同名參數(shù)實例
今天小編就為大家分享一篇Python可變參數(shù)會自動填充前面的默認(rèn)同名參數(shù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Python3交互式shell ipython3安裝及使用詳解
這篇文章主要介紹了Python3交互式shell ipython3安裝及使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07

