计算列表中数字平方和的函数

Spe*_*e43 2 python integer function list

我正在尝试编写一个函数sum_of_squares(xs)来计算列表xs中数字的平方和.例如,sum_of_squares([2,3,4])应返回4 + 9 + 16,即29:

这是我试过的:

import random

xs = []

#create three random numbers between 0 and 50

for i in range(3):
    xs.append(random.randint(0,50))

def sum_of_squares(xs):

#square the numbers in the list

    squared = i ** i

#add together the squared numbers

    sum_of_squares = squared + squared + squared

    return sum_of_squares

print (sum_of_squares(xs))
Run Code Online (Sandbox Code Playgroud)

现在这总是打印

12
Run Code Online (Sandbox Code Playgroud)

因为它将i视为列表中的整数数,而不是整数的值.我怎么说"将值乘以整数的值",因为列表中有多个整数可以得到平方值?

问这个问题让我尝试这个:

import random

xs = []

#create three random numbers between 0 and 50

for i in range(3):
    xs.append(random.randint(0,50))

def sum_of_squares(xs):

#square the numbers in the list

    for i in (xs):
        squared = i ** i

#add together the squared numbers

        sum_of_squares = squared + squared + squared

    return sum_of_squares

print (sum_of_squares(xs))
Run Code Online (Sandbox Code Playgroud)

但它似乎没有正确地平衡整数的值 - 我不确定它在做什么.看这个截图见截图一个可视化的Python演练.

bul*_*eam 5

def sum_of_squares(xs):
    return sum(x * x for x in xs)
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案非常好.我认为提问者要更难理解. (3认同)