Given a list of numbers like [1,2,3,4,5,6]
, how can I write code to multiply them all together, i.e. compute 1*2*3*4*5*6
?
ベストアンサー1
Python 3: use functools.reduce
:
>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1, 2, 3, 4, 5, 6])
720
Python 2: use reduce
:
>>> reduce(lambda x, y: x*y, [1, 2, 3, 4, 5, 6])
720
For compatible with 2 and 3 use Six (pip install six
), then:
>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720