一行列表中的平方和?

sum of squares in a list in one line?(一行列表中的平方和?)
本文介绍了一行列表中的平方和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

为了证明我做了某事.这是我的代码总和为三行.

To demonstrate I have done sth. This is my code do sum in three lines.

l=[1,2,3,4,5];
sumOfList=0

for i in l:
    sumOfList+=i*i;
print sumOfList

我很好奇我可以只用一行吗?

I am curious can I do it in just one line?

推荐答案

怎么样:

sum(map(lambda x:x*x,l))

我们也使用reduce:

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

我们可以取第一个元素,得到它的平方,然后将它添加到列表的头部,这样我们就可以确保它是平方的.然后我们继续使用reduce.不值得做所有这些工作,因为我们有更好的选择.

We can take the first element, get its square, then add it to the head of the list so we can make sure that it's squared. Then we continue using reduce. It isn't worth all that work, as we have better alternatives.

reduce(lambda x,y: x+y*y,[l[:1][0]**2]+l[1:])

出于好奇,我尝试比较三种解决方案,将 range 生成的 10000 个数的平方相加,并计算每个操作的执行时间.

Just out of curiosity, I tried to compare the three solutions to sum the squares of 10000 numbers generated by range, and compute the execution time of every operation.

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))

输出:

使用 list comprehension 更快

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

这篇关于一行列表中的平方和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)