我需要编写一个函数
一个数字的列表,然后将它们相乘。例子:
[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使用pip install 6
,那么:
>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
https://stackoverflow.com/questions/13840379/