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

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

相关文章:

mysql - 无法连接到 MySQL 服务器错误 111

linux - 在一行中从 linux 终端发送邮件

linux - 在 linux 中更改 VNC session 的分辨率

python - 使用 Python 处理 csv 文件时如何跳过标题?

python - 在 django Forms 中定义 css 类

Linux - 仅安装 redis-cli

linux - Linux Ubuntu下启动时自动运行程序

python - 在 Python 中计算 Pearson 相关性和显着性

linux - 单击选项卡时出现shell init问题,getcwd有什么问题?

python - Python中的退出代码