Python将列表中的所有数字相乘(7种不同方式)
给定一个列表,打印列表中所有数字相乘后得到的数值。
示例s:
Input : list1 = [1, 2, 3] Output : 6 Explanation: 1*2*3=6
Input : list1 = [3, 2, 4] Output : 24
方法1: Traversal
将乘积的值初始化为1(而不是0,因为0与任何东西相乘都返回0)。遍历到列表的末尾,将每个数字与乘积相乘。最后存储在乘积中的值将给出你的最终答案。
下面是上述方法的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))
输出
6 24
方法 2: 使用 numpy.prod()
我们可以使用numpy.prod() from import numpy来获得列表中所有数字的乘法。它根据乘法结果返回一个整数或一个浮点数。
下面是上述方法的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)
输出:
6 24
方法 3使用lambda函数。使用numpy.array
Lambda的定义不包括 “返回 “语句,它总是包含一个被返回的表达式。我们也可以把lambda的定义放在任何期望有函数的地方,而且我们根本不需要把它赋值给一个变量。这就是lambda函数的简单性。Python 中的 reduce() 函数接收了一个函数和一个列表作为参数。该函数被调用时有一个 lambda 函数和一个列表,然后返回一个新的减少的结果。这就对列表中的对子进行了重复操作。
下面是上述方法的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)
输出
6 24
方法4使用数学库的prod函数。使用math.prod
从Python 3.8开始,一个prod函数已经包含在标准库的数学模块中,因此不需要安装外部库。
下面是上述方法的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)
输出:
6 24
方法5:使用操作员模块的mul()函数。
首先,我们必须导入运算器模块,然后使用运算器模块的mul()函数将列表中的所有数值相乘。
# Python 3 program to multiply all numbers in # the given list by importing operator module from operator import* list1 = [1, 2, 3] m = 1 for i in list1: # multiplying all elements in the given list # using mul function of operator module m = mul(i, m) # printing the result print(m)
输出
6
方法6:使用按索引进行的遍历
# Python program to multiply all values in the # list using traversal def multiplyList(myList) : # Multiply elements one by one result = 1 for i in range(0,len(myList)): result = result * myList[i] return result # Driver code list1 = [1, 2, 3] list2 = [3, 2, 4] print(multiplyList(list1)) print(multiplyList(list2))
输出
6 24
方法7: 使用 itertools.accumulate
# Python3 program to multiply all values in the # list using lambda function and accumulate() from itertools import accumulate list1 = [1, 2, 3] list2 = [3, 2, 4] result1 = list(accumulate(list1, (lambda x, y: x * y))) result2 = list(accumulate(list2, (lambda x, y: x * y))) print(result1[-1]) print(result2[-1])
输出:
**6** **24**
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com