Python的functools.reduce用法


python 3.0以后, reduce已經不在built-in function里了, 要用它就得from functools import reduce.

reduce的用法

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

 

意思就是對sequence連續使用function, 如果不給出initial, 則第一次調用傳遞sequence的兩個元素, 以后把前一次調用的結果和sequence的下一個元素傳遞給function. 如果給出initial, 則第一次傳遞initial和sequence的第一個元素給function.

from functools import reduce  
reduce(lambda x,y: x+y, [1, 2, 3])  
輸出 6  
reduce(lambda x, y: x+y, [1,2,3], 9)  
輸出 15  
reduce(lambda x,y: x+y, [1, 2, 3], 7)  
輸出 13  

  

*functool標准庫還有很多功能,可以參考網上的資料


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM