【问题标题】:How to obtain the total sumation of an list and also its product using Numpy [duplicate]如何使用 Numpy 获取列表及其乘积的总和 [重复]
【发布时间】:2017-09-18 11:54:16
【问题描述】:

大家好,我是 Numpy 的新手,正在努力学习,但遇到了问题。假设我有一个列表,我想找到总数和产品。我可以在 vanilla python 中这样做:

numbers_list = [5,4,3,2,1]
total = sum(numbers_list)

product = 1
for x in numbers:
    product = product * x

总数应该是 15 和产品 120。但是我怎样才能使用 Numpy 呢?

【问题讨论】:

  • 查看np.prod
  • np.array(numbers_list).sum()np.array(numbers_list).prod()

标签: python python-3.x numpy python-2.x


【解决方案1】:

使用numpy.asarray将Python列表转化为Numpy数组,然后使用numpy.sumnumpy.prod分别计算总和和乘积,观察:

import numpy as np

numbers_list = [5,4,3,2,1]

numbers_np_array = np.asarray(numbers_list)

total = numbers_np_array.sum()
product = numbers_np_array.prod()

print("The total is: %d" % total)
print("The product is: %d" % product)

输出:

The total is: 15
The product is: 120

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2014-07-27
    • 1970-01-01
    • 2020-03-02
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多