Python 一行中列表中的平方和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26894227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:07:56  来源:igfitidea点击:

sum of squares in a list in one line?

pythonlistsum

提问by AlexWei

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

为了证明我已经做了某事。这是我的代码在三行中做总和。

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

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

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

我很好奇我可以在一行中完成吗?

采纳答案by AlexWei

What about :

关于什么 :

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

we also use reduce:

我们还使用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

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。因为我们有更好的选择,所以所有的工作都不值得。

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

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

只是出于好奇,我尝试比较三种解决方案,以求和由10000生成的数字的平方range,并计算每个操作的执行时间。

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

Output:

输出:

Using list comprehensionis faster

使用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

回答by Hackaholic

Yes, you can. Here it is using the sumfunction:

是的你可以。这里是使用sum函数:

l = [1,2,3,4,5]
print(sum(i*i for i in l))

回答by espang

For bigger list and when performance matters you should use numpy:

对于更大的列表以及当性能很重要时,您应该使用 numpy:

import numpy as np
l = [1,2,3,4,5]
arr = np.array(l)

np.sum(arr**2)
# or better:
np.dot(arr, arr)

回答by MattP

You could define a function and use list comprehension

您可以定义一个函数并使用列表理解

l = [2, 6, 10, 12, 16, 20]

def sumOfSquares(alist):
return ((sum([i**2 for i in alist]))-(sum(alist)**2)/len(alist))

print(sumOfSquares(l))