網站首頁 編程語言 正文
reduce函數原本在python2中也是個內置函數,不過在python3中被移到functools模塊中。
reduce函數先從列表(或序列)中取出2個元素執行指定函數,并將輸出結果與第3個元素傳入函數,輸出結果再與第4個元素傳入函數,…,以此類推,直到列表每個元素都取完。
1 reduce用法
對列表元素求和,如果不用reduce,我們一般常用的方法是for循環:
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))
可以看到,代碼量比較多,不夠優雅。如果使用reduce,那么代碼將非常簡潔:
from functools import reduce
a = [1, 2, 3, 4, 5]
def add(x, y): return x + y
print(reduce(add, a))
輸出結果為:
15
2 reduce與for循環性能對比
與內置函數map和filter不一樣的是,在性能方面,reduce相比較for循環來說沒有優勢,甚至在實際測試中
reduce比for循環更慢。
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循環耗時:', (t2 - t1))
print('reduce耗時:', (t3 - t2))
輸出結果如下:
for循環耗時: 0.009323899999999996
reduce耗時: 0.018477400000000005
因此,如果對性能要求苛刻,建議不用reduce, 如果希望代碼更優雅而不在意耗時,可以用reduce。
原文鏈接:https://blog.csdn.net/huachao1001/article/details/124060003
相關推薦
- 2022-06-29 python中py文件與pyc文件相互轉換的方法實例_python
- 2022-10-27 教你使用Python?的?Template?類生成文件報告_python
- 2023-02-06 C++11中longlong超長整型和nullptr初始化空指針_C 語言
- 2022-10-22 Go語言同步等待組sync.WaitGroup結構體對象方法詳解_Golang
- 2022-12-29 R語言apply系列函數實例詳解_R語言
- 2022-07-09 Android實現app開機自啟動功能_Android
- 2021-12-02 Flutter將整個App變為灰色的簡單實現方法_Android
- 2022-12-10 C++中如何將數據保存為CSV文件_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支