我需要编写一个函数,该函数接受数字的列表,然后将它们相乘。例如:[1,2,3,4,5,6]
会给我1*2*3*4*5*6
。我真的需要你的帮助。
发布于 2012-12-12 21:03:19
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兼容,请使用pip install six
,然后:
>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
发布于 2012-12-12 21:03:07
您可以使用:
import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)
有关说明,请参阅reduce
和operator.mul
文档。
您需要在Python 3+中使用import functools
行。
发布于 2015-09-07 01:54:16
我将使用numpy.prod
来执行该任务。见下文。
import numpy as np
mylist = [1, 2, 3, 4, 5, 6]
result = np.prod(np.array(mylist))
https://stackoverflow.com/questions/13840379
复制相似问题