Python|列表中正方形的乘积
Python作为魔术师的语言,可用于以简单简洁的方式执行许多繁琐和重复的任务,并且拥有充分利用该工具的知识总是有用的。一个这样的小应用程序可以是仅在一行中找到列表平方的乘积。让我们讨论可以执行此操作的某些方式。
方法 #1:使用reduce()
+ lambda
lambda 函数在一行中执行冗长任务的强大功能,允许它与用于累积子问题的 reduce 结合来执行此任务。仅适用于Python 2。
# Python code to demonstrate
# Product of Squares in List
# 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
# Product of Squares in List
res = reduce(lambda i, j: i * j*j, [test_list[:1][0]**2]+test_list[1:])
# printing result
print ("The product of squares of list is : " + str(res))
输出 :
The original list is : [3, 5, 7, 9, 11]
The product of squares of list is : 108056025
方法 #2:使用map() + loop
使用 map函数进行积分和外部积函数执行平方数的乘积也可以获得类似的解决方案。
# Python3 code to demonstrate
# Product of Squares in List
# using sum() + max()
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [3, 5, 7, 9, 11]
# printing original list
print ("The original list is : " + str(test_list))
# using sum() + max()
# Product of Squares in List
res = prod(map(lambda i : i * i, test_list))
# printing result
print ("The product of squares of list is : " + str(res))
输出 :
The original list is : [3, 5, 7, 9, 11]
The product of squares of list is : 108056025