给定一个像[1,2,3,4,5,6]这样的数字列表,我如何编写代码将它们相乘,即计算1*2*3*4*5*6?


当前回答

那么使用递归呢?

def multiply(lst):
    if len(lst) > 1:
        return multiply(lst[:-1])* lst[-1]
    else:
        return lst[0]

其他回答

如果你想避免导入任何东西,避免Python中更复杂的部分,你可以使用一个简单的for循环:

nums = [1, 2, 3]

product = 1  # Don't use 0 here, otherwise, you'll get zero 
             # because anything times zero will be zero.
for num in nums:
    product *= num

Python 3:使用functools.reduce:

>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1, 2, 3, 4, 5, 6])
720

Python 2:使用reduce:

>>> reduce(lambda x, y: x*y, [1, 2, 3, 4, 5, 6])
720

为了兼容2和3,请使用Six (pip install Six),然后:

>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

在Python 3.8及以上版本中,数学标准库模块为此提供了.prod:

数学。Prod(可迭代,*,start=1)

该方法返回起始值(默认值:1)乘以数字可迭代对象的乘积:

import math
math.prod([1, 2, 3, 4, 5, 6])
# 720

如果可迭代对象为空,将产生1(或者起始值,如果提供)。

我会使用numpy。执行任务的提示:

import numpy as np

mylist = [1, 2, 3, 4, 5, 6] 
result = np.prod(np.array(mylist))  

一种使用方法是math.prod() 例如:

import math
arr = [1, 2, 3, 4]
print(math.prod(arr))

另一种方法是numpy.prod() 这是另一个要导入的库

import numpy
arr = [1, 2, 3, 4]
print(numpy.prod(arr))