如何将列表中的所有元素彼此相乘?

ral*_*llo 0 python math list multiplication operator-keyword

我试图将列表中的所有数字彼此相乘

a = [2,3,4]
for number in a:
        total = 1 
        total *= number 
return total 
Run Code Online (Sandbox Code Playgroud)

输出应该是 24,但由于某种原因我得到 4。为什么会这样?

Jon*_*hez 5

每次循环迭代都将 total 初始化为 1。

代码应该是(如果你真的手动完成):

a = [2, 3, 4]
total = 1
for i in a:
    total *= i
Run Code Online (Sandbox Code Playgroud)

这解决了您当前的问题,但是,如果您使用的是 Python 3.8 或更高版本,则此功能在math库中:

import math
a = [2, 3, 4]
total = math.prod(a)
Run Code Online (Sandbox Code Playgroud)