如何将列表中的所有项目与 Python 相乘? [英] How can I multiply all items in a list together with Python?
本文介绍了如何将列表中的所有项目与 Python 相乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要写一个函数一个列表数字并将它们相乘在一起.例子:[1,2,3,4,5,6]
会给我1*2*3*4*5*6
.我真的可以用你的帮助.
解决方案
Python 3:使用 functools.reduce
:
Python 2:使用reduce
:
为了兼容2和3使用pip install 6
,然后:
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
这篇关于如何将列表中的所有项目与 Python 相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文