reduce(fun,seq)函數用於將在其參數中傳遞的特定函數應用於傳遞的序列中提到的所有列表元素。此函數在“functools”模塊中定義。
工作方式:
- 第一步,選擇序列的前兩個元素並獲得結果。
- 下一步是對先前獲得的結果應用相同的函數,並且緊隨第二個元素之後的數字將被再次存儲。
- 繼續此過程,直到容器中沒有剩餘元素為止。
- 返回的最終結果將返回並打印在控製台上。
# python code to demonstrate working of reduce()
# importing functools for reduce()
import functools
# initializing list
lis = [ 1 , 3, 5, 6, 2, ]
# using reduce to compute sum of list
print ("The sum of the list elements is:",end="")
print (functools.reduce(lambda a,b:a+b,lis))
# using reduce to compute maximum element from list
print ("The maximum element of the list is:",end="")
print (functools.reduce(lambda a,b:a if a > b else b,lis))
輸出:
The sum of the list elements is:17 The maximum element of the list is:6
Using Operator Functions
reduce()也可以與運算符函數結合使用,以實現與lambda函數相似的函數,並使代碼更具可讀性。
# python code to demonstrate working of reduce()
# using operator functions
# importing functools for reduce()
import functools
# importing operator for operator functions
import operator
# initializing list
lis = [ 1 , 3, 5, 6, 2, ]
# using reduce to compute sum of list
# using operator functions
print ("The sum of the list elements is:",end="")
print (functools.reduce(operator.add,lis))
# using reduce to compute product
# using operator functions
print ("The product of list elements is:",end="")
print (functools.reduce(operator.mul,lis))
# using reduce to concatenate string
print ("The concatenated product is:",end="")
print (functools.reduce(operator.add,["geeks","for","geeks"]))
輸出量
The sum of the list elements is:17 The product of list elements is:180 The concatenated product is:geeksforgeeks
reduce()和accumulate()
reduce()和accumulate()均可用於計算序列元素的總和。但是這兩者在實現方麵都有差異。
- reduce()在“functools”模塊中定義,accumulate()在“itertools”模塊中定義。
- reduce()存儲中間結果,並且僅返回最終的求和值。而accumulate()返回包含中間結果的列表。返回的列表的最後一個數字是列表的總和。
- reduce(fun,seq)將函數作為第一參數,將序列作為第二參數。相反,accumulate(seq,fun)將序列作為第一個參數,將函數用作第二個參數。
# python code to demonstrate summation
# using reduce() and accumulate()
# importing itertools for accumulate()
import itertools
# importing functools for reduce()
import functools
# initializing list
lis = [ 1, 3, 4, 10, 4 ]
# priting summation using accumulate()
print ("The summation of list using accumulate is:",end="")
print (list(itertools.accumulate(lis,lambda x,y:x+y)))
# priting summation using reduce()
print ("The summation of list using reduce is:",end="")
print (functools.reduce(lambda x,y:x+y,lis))
輸出:
The summation of list using accumulate is:[1, 4, 8, 18, 22] The summation of list using reduce is:22
相關用法
注:本文由純淨天空篩選整理自 reduce() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。