<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # 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`循環更簡潔,并且性能明顯更好。 * * * * * *
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看