我试着写一个平方和(xs)函数来计算列表xs中数字的平方和。例如,平方和([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))
现在这个总是印出来的12
因为它把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))
但它似乎没有正确地对正整数的值-我不确定它在做什么。请参见本屏幕截图中的Visualize Python演练。