歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python的functools.reduce用法

Python的functools.reduce用法

日期:2017/3/1 9:18:42   编辑:Linux編程

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標准庫還有很多功能,可以參考網上的資料

下面關於Python的文章您也可能喜歡,不妨看看:

Linux下Python的安裝以及注意事項 http://www.linuxidc.com/Linux/2015-11/124861.htm

Ubuntu 14.04 下安裝使用Python rq模塊 http://www.linuxidc.com/Linux/2015-08/122441.htm

無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved