# Python `reduce()`函數
> 原文: [https://thepythonguru.com/python-builtin-functions/reduce/](https://thepythonguru.com/python-builtin-functions/reduce/)
* * *
于 2020 年 1 月 7 日更新
* * *
`reduce()`函數接受一個函數和一個序列并返回如下計算的單個值:
1. 最初,使用序列中的前兩項調用該函數,然后返回結果。
2. 然后使用在步驟 1 中獲得的結果和序列中的下一個值再次調用該函數。 這個過程一直重復,直到序列中有項目為止。
`reduce()`函數的語法如下:
**語法**:`reduce(function, sequence[, initial]) -> value`
提供`initial`值時,將使用`initial`值和序列中的第一項調用該函數。
在 Python 2 中,`reduce()`是一個內置函數。 但是,在 Python 3 中,它已移至`functools`模塊。 因此,要使用它,必須先按以下步驟導入它:
```py
from functools import reduce # only in Python 3
```
這是添加列表中所有項目的示例。
```py
>>>
>>> from functools import reduce
>>>
>>> def do_sum(x1, x2): return x1 + x2
...
>>>
>>> reduce(do_sum, [1, 2, 3, 4])
10
>>>
```
試試看:
```py
from functools import reduce
def do_sum(x1, x2):
return x1 + x2
print(reduce(do_sum, [1, 2, 3, 4]))
```
此`reduce()`調用執行以下操作:
```py
(((1 + 2) + 3) + 4) => 10
```
前面的`reduce()`調用在功能上等同于以下內容:
```py
>>>
>>> def my_reduce(func, seq):
... first = seq[0]
... for i in seq[1:]:
... first = func(first, i)
... return first
...
>>>
>>> my_reduce(do_sum, [1, 2, 3, 4])
10
>>>
```
試一試:
```py
def do_sum(x1, x2):
return x1 + x2
def my_reduce(func, seq):
first = seq[0]
for i in seq[1:]:
first = func(first, i)
return first
print(my_reduce(do_sum, [1, 2, 3, 4]))
```
但是,`reduce()`調用比`for`循環更簡潔,并且性能明顯更好。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象