程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python basics] detailed explanation of reduce function

編輯:Python

reduce The function was originally python2 Is also a built-in function , But in the python3 To be moved to functools Module .

reduce The function starts from the list ( Or sequence ) Remove from 2 An element executes the specified function , And compare the output result with the 3 An element is passed into the function , The output results are then compared with the 4 An element is passed into the function ,…, And so on , Until every element of the list is taken .

1 reduce usage
Sum the list elements , If not reduce, Our common method is for loop :

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))

You can see , A lot of code , Not elegant enough . If you use reduce, Then the code will be very concise :

from functools import reduce
a = [1, 2, 3, 4, 5]
def add(x, y): return x + y
print(reduce(add, a))

The output is :

15
1

2 reduce And for Cycle performance comparison
With built-in functions map and filter The difference is , In terms of performance ,reduce Comparison for There is no advantage in terms of circulation , Even in actual testing

reduce Than for Slower cycle .

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 Cycle time :', (t2 - t1))
print('reduce Time consuming :', (t3 - t2))

The output is as follows :

for Cycle time : 0.009323899999999996
reduce Time consuming : 0.018477400000000005

therefore , If you are demanding on performance , It is not recommended that reduce, If you want the code to be more elegant and don't care about time consuming , It can be used reduce.
————————————————
Copyright notice : This paper is about CSDN Blogger 「 Uncle Zou Zhao 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/huachao1001/article/details/124060003

Link to the original text :https://www.bitpy.cn/a/feed0c7b-1535-4830-9fd5-d6da86aa566e


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved