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


当前回答

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

其他回答

你可以使用:

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

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

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

今天发现了这个问题,但我注意到它没有在列表中有None的情况。所以,完整的解决方案是:

from functools import reduce

a = [None, 1, 2, 3, None, 4]
print(reduce(lambda x, y: (x if x else 1) * (y if y else 1), a))

在加法的情况下,我们有:

print(reduce(lambda x, y: (x if x else 0) + (y if y else 0), a))

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(或者起始值,如果提供)。

简单的方法是:

import numpy as np
np.exp(np.log(your_array).sum())