Python中累加可以使用函数sum()来实现,
例:
numpy.sum(A)---数组内所有元素之和,A---数组
import numpy as np a = np.array([[1,3,6],[9,5,6]]) b = np.sum(a) print(b)
打印
numpy.sum(A ,axis=1)---数组内所有元素之和,axis=1一行的元素之和
import numpy as np a = np.array([[1,3,6],[9,5,6]]) b = np.sum(a , axis=1) print(b)
sum函数介绍:
python自带的sum函数(或者Numpy中的sum函数),
无参时,所有全加;
axis=0,按列相加;
axis=1,按行相加;
import numpy as np #python中自带的sum print(sum([[1,2,3],[4,5,5]])) print(sum([[1,2,3],[4,5,5]],axis=0)) print(sum([[1,2,3],[4,5,5]],axis=1)) #Numpy中的sum a = np.sum([[1,2,3], [4,5,5]]) #无参 print(a) print(a.shape) a = np.sum([[1,2,3], [4,5,5]],axis=0) #axis=0, 按列相加 print(a) print(a.shape) a = np.sum([[1,2,3], [4,5,5]],axis=1) #axis=1, 按行相加 print(a) print(a.shape)
20 [5 7 8] [ 6 14] 20 () [5 7 8] (3,) [ 6 14] (2,)
更多Python相关技术文章,请访问Python教程栏目进行学习!