<p>怎么办:</p>
<pre><code>sum(map(lambda x:x*x,l))
</code></pre>
<p>我们还使用<code>reduce</code>:</p>
<pre><code>print reduce(lambda x,y: x+y*y,l) # as pointed by @espang reduce(lambda x,y: x+y*y,l) is only ok, when the first value is 1 (because 1*1 == 1). The first value is not squared
</code></pre>
<p>我们可以取第一个元素,得到它的平方,然后将它添加到列表的头部,这样我们就可以确保它是平方的。然后我们继续使用reduce。这不值得这么做,因为我们有更好的选择。</p>
<pre><code>reduce(lambda x,y: x+y*y,[l[:1][0]**2]+l[1:])
</code></pre>
<p>出于好奇,我试着比较这三个解,求出由<code>range</code>生成的<code>10000</code>个数的平方和,并计算出每个操作的执行时间。</p>
<pre><code>l=range(10000)
from datetime import datetime
start_time = datetime.now()
print reduce(lambda x,y: x+y*y,l)
print('using Reduce numbers: {}'.format(datetime.now() - start_time))
from datetime import datetime
start_time = datetime.now()
print sum(map(lambda x:x*x,l))
print('Sum after map square operation: {}'.format(datetime.now() - start_time))
from datetime import datetime
start_time = datetime.now()
print sum( i*i for i in l)
print('using list comprehension to sum: {}'.format(datetime.now() - start_time))
</code></pre>
<p>输出:</p>
<p>使用<code>list comprehension</code>更快</p>
<pre><code>333283335000
using Reduce numbers: 0:00:00.003371
333283335000
Sum after map square operation: 0:00:00.002044
333283335000
using list comprehension to sum: 0:00:00.000916
</code></pre>