【问题标题】:How do I multiply all the elements inside a list by each other? [duplicate]如何将列表中的所有元素相乘? [复制]
【发布时间】:2020-04-17 01:55:21
【问题描述】:

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

a = [2,3,4]
for number in a:
        total = 1 
        total *= number 
return total 

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

【问题讨论】:

  • "total" 在每次循环迭代中设置为 1。你不想这样。
  • 从 Py3.8 开始:import mathproduct = math.prod([2, 3, 4])

标签: python list math operator-keyword multiplication


【解决方案1】:

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

代码应该是(如果您真的想要手动执行):

a = [2, 3, 4]
total = 1
for i in a:
    total *= i

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

import math
a = [2, 3, 4]
total = math.prod(a)

【讨论】:

    【解决方案2】:

    方法一: 使用 numpy 包中的 prod 函数。

    import numpy
         ...: a = [1,2,3,4,5,6]
         ...: b = numpy.prod(a)
    
    In [128]: b
    Out[128]: 720
    

    方法 2: 在 Python 3.8 中, prod 被添加到数学模块中:

    math.prod(iterable, *, start = 1)

    math.prod(a) 
    

    也会这样做

    【讨论】:

      【解决方案3】:

      如果您不想使用 numpy,请使用 reduce 函数。

      from functools import reduce
      reduce(lambda x, y: x*y, [1, 2, 3, 4, 5])
      

      【讨论】:

      • reduce(operator.mul, [1, 2, 3, 4, 5])
      【解决方案4】:

      之所以为4 是因为在for 循环中,您执行total = 1,然后在每次迭代中将total 与当前编号相乘。所以它会循环到最后,最后一个元素是4,你把4乘以1,所以现在总数是4。

      如果你想在一个列表中包含多个所有元素。我建议你使用numpy.prod:

      import numpy as np
      list = [2,3,4,5]
      final = np.prod(list)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-16
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 2017-04-06
        相关资源
        最近更新 更多