日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python中reduce函數(shù)詳解_python

作者:走召大爺 ? 更新時間: 2022-08-04 編程語言

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)勢,甚至在實(shí)際測試中

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。

原文鏈接:https://blog.csdn.net/huachao1001/article/details/124060003

欄目分類
最近更新