Python中数组及矩阵的大小

来源:互联网 发布:qq手机型号修改软件 编辑:程序博客网 时间:2024/04/30 10:15

Python中数组及矩阵的大小


写在前面:最近看了caffe以及rcnn-depth的代码,感慨什么时候自己才能写出这样的代码。但是只感慨是没有用的,还是动手码才行!显而易见的是,像我目前这种敲两行代码都要问google是肯定不行,因此往后的一段时间会利用空余时间对目前接触比较多的Python, Matlab及C++中一些容易混淆的问题稍作总结,以期能够慢慢提高的码代码水平。


在上篇博文中介绍了python中常见的二维数组:list与numpy.array。在很多情况下我们需要获取数组的大小,阅读过一些python代码可以发现,常见的方法一般有len, size, shape这三种,那么这三种方法分别应用于那些场合?有什么区别?本文将通过示例来探讨这些问题。


In [2]:
import numpy as npa = [[1,2,3,4], [5,6,7,8], [9, 10, 11, 12]]b = np.array(a)print type(a)print aprint type(b)print b



<type 'list'>[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]<type 'numpy.ndarray'>[[ 1  2  3  4] [ 5  6  7  8] [ 9 10 11 12]]




In [5]:
print len(a), len(a[0])



3 4

---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-5-2f7fbe06ffd7> in <module>()      1 print len(a), len(a[0])----> 2 print size(a)NameError: name 'size' is not defined




In [9]:
print size(a)



---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-9-17932fb9dbd4> in <module>()----> 1 print size(a)NameError: name 'size' is not defined




In [6]:
print a.size



---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)<ipython-input-6-d6180f130c7b> in <module>()----> 1 print a.sizeAttributeError: 'list' object has no attribute 'size'




In [7]:
print shape(a)



---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-7-5b1e858da0b7> in <module>()----> 1 print shape(a)NameError: name 'shape' is not defined




In [8]:
print a.shape



---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)<ipython-input-8-2f66fe9ba9f6> in <module>()----> 1 print a.shapeAttributeError: 'list' object has no attribute 'shape'




由上可知,list只支持len(), 该方法实际是调用了对象的__len__(self)方法


In [12]:
print len(b)print b.sizeprint b.shape



312(3, 4)




对比之下,numpy.array同时支持len, size, shape, 注意看三者返回值的区别。


此外,numpy中还提供matrix的数据类型,具体请看:


In [17]:
c = np.mat(a)print type(c)print cd = np.mat(b)print type(d)print dprint len(d)print d.sizeprint d.shape



<class 'numpy.matrixlib.defmatrix.matrix'>[[ 1  2  3  4] [ 5  6  7  8] [ 9 10 11 12]]<class 'numpy.matrixlib.defmatrix.matrix'>[[ 1  2  3  4] [ 5  6  7  8] [ 9 10 11 12]]312(3, 4)




从上面的例子可以看出,martix支持由list和numpy.array创建,同时支持len, size以及shape. 另外从numpy.matrix上可以了解到,matrix相对于list和numpy.array而言,支持*(矩阵相乘),**(矩阵幂)等。


In [20]:
print c*d.T



[[ 30  70 110] [ 70 174 278] [110 278 446]]






补充:numpy中有一个numpy.shape()函数,支持array_like如list, array等,返回tuple of ints, 具体可查看其帮助函数。
来自为知笔记(Wiz)
        </div>
原创粉丝点击