且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将列表中的所有项目与 Python 相乘?

更新时间:2023-02-10 16:58:41

Python 3:使用 functools.reduce:

>>>从 functools 导入减少>>>减少(λ x,y:x * y,[1,2,3,4,5,6])720

Python 2:使用reduce:

>>>减少(λ x,y:x * y,[1,2,3,4,5,6])720

为了兼容2和3使用pip install 6,然后:

>>>从六.moves导入减少>>>减少(λ x,y:x * y,[1,2,3,4,5,6])720

I need to write a function that takes a list of numbers and multiplies them together. Example: [1,2,3,4,5,6] will give me 1*2*3*4*5*6. I could really use your help.

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 pip install six, then:

>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720