網(wǎng)站首頁 編程語言 正文
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
相關(guān)推薦
- 2022-09-16 Pandas數(shù)值排序?sort_values()的使用_python
- 2022-12-23 淺析Go語言中Channel的各種用法_Golang
- 2022-10-16 pytorch中.numpy()、.item()、.cpu()、.detach()以及.data的使
- 2022-04-10 Blazor頁面組件用法介紹_基礎(chǔ)應(yīng)用
- 2022-12-14 Rocksdb?Memtable數(shù)據(jù)結(jié)構(gòu)源碼解析_Android
- 2022-10-03 Pandas數(shù)據(jù)集的分塊讀取的實(shí)現(xiàn)_python
- 2022-07-29 Pytest框架?conftest.py文件的使用詳解_python
- 2023-04-03 C++作用域與函數(shù)重載的實(shí)現(xiàn)_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支