擅长:python、mysql、java
<p>对数组求和的python方法是使用<a href="https://docs.python.org/3/library/functions.html#sum" rel="nofollow noreferrer">^{<cd1>}</a>。出于其他目的,有时可以使用<a href="https://docs.python.org/3/library/functools.html#functools.reduce" rel="nofollow noreferrer">^{<cd2>}</a>(来自<a href="https://docs.python.org/3/howto/functional.html#the-functools-module" rel="nofollow noreferrer">^{<cd3>}</a>模块)和<a href="https://docs.python.org/3/library/operator.html#module-operator" rel="nofollow noreferrer">^{<cd4>}</a>模块的组合,例如:</p>
<pre><code>def product(xs):
return reduce(operator.mul, xs, 1)
</code></pre>
<p>注意<code>reduce</code>实际上是一个<code>foldl</code>,用Haskell的术语来说。没有特殊的语法来执行折叠,没有内置的<code>foldr</code>,并且实际使用<code>reduce</code>与非关联运算符被认为是错误的风格。</p>
<p>使用高阶函数是非常Python的;它很好地利用了Python的原则,即一切都是对象,包括函数和类。你说得对,有些Python不喜欢羔羊,但主要是因为当它们变得复杂时,它们往往不太可读。</p>