如何使用 Numpy 获取列表的总和及其乘积

How to obtain the total sumation of an list and also its product using Numpy

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

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

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

总数应该是 15,乘积应该是 120。但是我如何使用 Numpy 来做呢?

将Python列表转换为Numpy数组,使用numpy.asarray and then use numpy.sum and numpy.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