【问题标题】:Multiply list numbers and print the total (aggregation) [duplicate]将列表数字相乘并打印总数(聚合)[重复]
【发布时间】:2019-01-04 11:30:50
【问题描述】:

我正在尝试创建一个基本的 Python 脚本,它允许我将列表中的每个数字相乘并打印总数。

例如,如果我的列表包含 2、5、1,我希望脚本将 2 * 5 * 1 相乘得到 10。由于某种原因,我无法生成这个,我已经能够生成它通过将数字相加(您可以在下面看到),但是当我将第 8 行更改为相乘时,它并没有给我预期的结果(在上面的示例中,它给了我 30 而不是预期的 10)。

不正确的乘法列表总数:

# input list
numbers = [2, 5, 1]
# output list
total = 0
# for each number in the list:
for number in numbers:
    # update total
    total = total + number * number
# print the total
print(total)

成功将列表中的数字相加的脚本:

# input list
numbers = [2, 5, 1]
# output list
total = 0
# for each number in the list:
for number in numbers:
    # update total
    total = total + number
# print total
print(total)

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    做这些事情的惯用方式是reduce — 字面意思是逐个元素“减少”您的序列元素并最终得到单个值。如果你需要乘法,你可以使用operator.mul——以编程方式进行乘法:

    from functools import reduce
    from operator import mul
    
    total = reduce(mul, [2, 5, 1])
    

    【讨论】:

      【解决方案2】:

      要将列表中的数字相乘并打印总数,您需要将总数设置为 1,并且需要使用 *= 运算符。这只是意味着“[左侧表达式] = [自身] * [右侧表达式]”

      # input list
      numbers = [2, 5, 1]
      # output list
      total = 1
      # for each number in the list:
      for number in numbers:
          # update total
          total *= number
      # print total
      print(total)
      

      这会打印 10 (2 * 5 * 1 = 10)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-23
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 2020-12-19
        相关资源
        最近更新 更多