gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:22:03 27 4
gpt4 key购买 nike

我需要编写一个函数一个数字的列表,然后将它们相乘。例子:[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

关于python - 如何将列表中的所有项目与 Python 相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13840379/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com