Python |将列表中的所有数字相乘(4种不同方式)

给定一个列表,打印列表中所有数字相乘后得到的值。 例如:

null
Input :  list1 = [1, 2, 3] Output : 6 Explanation: 1*2*3=6 Input : list1 = [3, 2, 4] Output : 24 

方法1:遍历

将乘积的值初始化为1(不是0,因为0乘以任何值都返回零)。遍历到列表末尾,将每个数字与乘积相乘。最后存储在产品中的值将给出最终答案。 下面是上述方法的Python实现:

python

# Python program to multiply all values in the
# list using traversal
def multiplyList(myList) :
# Multiply elements one by one
result = 1
for x in myList:
result = result * x
return result
# Driver code
list1 = [ 1 , 2 , 3 ]
list2 = [ 3 , 2 , 4 ]
print (multiplyList(list1))
print (multiplyList(list2))


输出:

624 

方法2:使用numpy。prod()

我们可以使用 努比。prod() 从import numpy获取列表中所有数字的乘法。它根据乘法结果返回整数或浮点值。 下面是上述方法的Python3实现:

Python3

# Python3 program to multiply all values in the
# list using numpy.prod()
import numpy
list1 = [ 1 , 2 , 3 ]
list2 = [ 3 , 2 , 4 ]
# using numpy.prod() to get the multiplications
result1 = numpy.prod(list1)
result2 = numpy.prod(list2)
print (result1)
print (result2)


输出:

624 

方法3使用lambda函数:使用numpy。大堆

Lambda的定义不包括 “返回” 语句,它始终包含返回的表达式。我们也可以将lambda定义放在任何需要函数的地方,而且根本不需要将它赋给变量。这就是lambda函数的简单性。这个 减少 Python中的函数接受函数和列表作为参数。使用lambda函数、list和n调用该函数 返回结果 。这会对列表中的对执行重复操作。 下面是上述方法的Python3实现:

Python3

# Python3 program to multiply all values in the
# list using lambda function and reduce()
from functools import reduce
list1 = [ 1 , 2 , 3 ]
list2 = [ 3 , 2 , 4 ]
result1 = reduce (( lambda x, y: x * y), list1)
result2 = reduce (( lambda x, y: x * y), list2)
print (result1)
print (result2)


输出:

624 

方法4使用数学库的prod函数:使用数学。戳

从Python3.8开始,标准库的数学模块中包含了一个prod函数,因此无需安装外部库。 下面是上述方法的Python3实现:

Python3

# Python3 program to multiply all values in the
# list using math.prod
import math
list1 = [ 1 , 2 , 3 ]
list2 = [ 3 , 2 , 4 ]
result1 = math.prod(list1)
result2 = math.prod(list2)
print (result1)
print (result2)


输出:

624 

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享