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


当前回答

你可以使用:

import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)

参见约简和算子。Mul文档进行解释。

你需要在Python 3+中导入functools行。

其他回答

nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))

你可以使用:

import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)

参见约简和算子。Mul文档进行解释。

你需要在Python 3+中导入functools行。

那么使用递归呢?

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

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

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

import numpy as np

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