Python??reduce()函數(shù)的用法示例代碼
Python reduce()函數(shù)的用法
reduce()函數(shù)也是Python內(nèi)置的一個高階函數(shù)。reduce()函數(shù)接收的參數(shù)和 map()類似,一個函數(shù) f,一個list,但行為和 map()不同,reduce()傳入的函數(shù) f 必須接收兩個參數(shù),reduce()對list的每個元素反復(fù)調(diào)用函數(shù)f,并返回最終結(jié)果值。
reduce()函數(shù)會對參數(shù)序列中的元素進行累積
語法結(jié)構(gòu)
reduce(function, iterable[, initializer])
參數(shù)說明
- function: 函數(shù),有兩個參數(shù)
- iterable: 可迭代對象
- initializer: 初始參數(shù)(可選)
返回值
返回函數(shù)計算結(jié)果
綜上所述,reduce()函數(shù)將一個數(shù)據(jù)集合中的所有數(shù)據(jù)進行下列操作,先從數(shù)據(jù)集合中取出2個元素執(zhí)行指定函數(shù)function,并將輸出結(jié)果與第3個元素傳入function函數(shù),輸出結(jié)果再與第4個元素傳入function函數(shù)進行計算,以此類推,直到列表每個元素都取完進行累積,最終返回計算結(jié)果
提示Tips
在python3中,內(nèi)置函數(shù)中已經(jīng)沒有reduce()函數(shù)了,它現(xiàn)在被放置在functools模塊里,如果想要使用它,則需要通過引入functools模塊來調(diào)用reduce()函數(shù)
from functools import reduce
示例1
from functools import reduce
# 兩數(shù)相加
def add(x,y):
return x + y
# 計算1 + 2 + 3 + ... + 100的和
sum1 = reduce(add, range(1, 101))
print(sum1) # 5050
# 計算列表和:1+2+3+4+5
# 使用lambda匿名函數(shù)+reduce()函數(shù)
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])
print(sum2) # 15
sum3 = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 6)
# 21 = 6 + 1 + 2 + 3 + 4 + 5
print(sum3) # 21示例2
from functools import reduce lst = [1,2,3,4,5] # 120 = 1 * 2 * 3 * 4 * 5 print(reduce(lambda x,y:x*y,lst)) # 120
示例3
from functools import reduce str1="abcdefg" # gfedcba print(reduce(lambda x,y:y+x, str1))
示例4
from functools import reduce
sentences = ['Hello World!! hello Andy']
# 統(tǒng)計字符串'Hello'出現(xiàn)的次數(shù)
word_count =reduce(lambda a,x:a+x.count("Hello"), sentences, 0)
print(word_count) # 1【Python基礎(chǔ)】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)文章
基于深度學(xué)習(xí)和OpenCV實現(xiàn)目標檢測
這篇文章主要介紹了通過使用OpenCV進行基于深度學(xué)習(xí)的對象檢測以及使用OpenCV檢測視頻,文中的示例代碼講解詳細,需要的可以參考一下2021-12-12
Pandas中df.loc[]與df.iloc[]的用法與異同?
本文主要介紹了Pandas中df.loc[]與df.iloc[]的用法與異同,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧?2022-07-07
Python 解析pymysql模塊操作數(shù)據(jù)庫的方法
這篇文章主要介紹了Python 解析pymysql模塊操作數(shù)據(jù)庫的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02
基于Python實現(xiàn)實時監(jiān)控CPU使用率
這篇文章主要為大家介紹了一款手寫編程代碼的小腳本,能夠輕松在界面上展示:利用Python實時監(jiān)控CPU使用率,隨時展現(xiàn)。也無需下載管理軟件,感興趣的可以了解一下2022-04-04
python3利用Dlib19.7實現(xiàn)人臉68個特征點標定
這篇文章主要為大家詳細介紹了python3利用Dlib19.7實現(xiàn)人臉68個特征點標定,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02
pycharm利用pyspark遠程連接spark集群的實現(xiàn)
由于工作需要,利用spark完成機器學(xué)習(xí)。因此需要對spark集群進行操作。所以利用pycharm和pyspark遠程連接spark集群。感興趣的可以了解一下2021-05-05

