📜  Python|列表中的平方和

📅  最后修改于: 2022-05-13 01:54:29.871000             🧑  作者: Mango

Python|列表中的平方和

Python作为魔术师的语言,可用于以简单简洁的方式执行许多繁琐和重复的任务,并且拥有充分利用该工具的知识总是有用的。一个这样的小应用程序可以仅在一行中找到列表的平方和。让我们讨论可以执行此操作的某些方式。

方法 #1:使用reduce() + lambda
lambda 函数在一行中执行冗长任务的强大功能,允许它与用于累积子问题的 reduce 结合来执行此任务。仅适用于Python 2。

# Python code to demonstrate  
# sum of squares 
# using reduce() + lambda
  
# initializing list
test_list = [3, 5, 7, 9, 11]
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# using reduce() + lambda
# sum of squares 
res = reduce(lambda i, j: i + j * j, [test_list[:1][0]**2]+test_list[1:])
  
# printing result
print ("The sum of squares of list is : " + str(res))
输出 :
The original list is : [3, 5, 7, 9, 11]
The sum of squares of list is : 285

方法 #2:使用map() + sum()
类似的解决方案也可以使用 map函数来积分和求和函数来执行平方数的求和。

# Python3 code to demonstrate  
# sum of squares 
# using sum() + max()
  
# initializing list
test_list = [3, 5, 7, 9, 11]
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# using sum() + max()
# sum of squares 
res = sum(map(lambda i : i * i, test_list))
  
# printing result
print ("The sum of squares of list is : " + str(res))
输出 :
The original list is : [3, 5, 7, 9, 11]
The sum of squares of list is : 285