Python中数组及矩阵的大小
写在前面:最近看了caffe以及rcnn-depth的代码,感慨什么时候自己才能写出这样的代码。但是只感慨是没有用的,还是动手码才行!显而易见的是,像我目前这种敲两行代码都要问google是肯定不行,因此往后的一段时间会利用空余时间对目前接触比较多的Python, Matlab及C++中一些容易混淆的问题稍作总结,以期能够慢慢提高的码代码水平。
在上篇博文中介绍了python中常见的二维数组:list与numpy.array。在很多情况下我们需要获取数组的大小,阅读过一些python代码可以发现,常见的方法一般有len, size, shape这三种,那么这三种方法分别应用于那些场合?有什么区别?本文将通过示例来探讨这些问题。
In [2]:
import numpy as np
a = [[1,2,3,4], [5,6,7,8], [9, 10, 11, 12]]
b = np.array(a)
print type(a)
print a
print type(b)
print b
In [5]:
print len(a), len(a[0])
In [9]:
print size(a)
In [6]:
print a.size
In [7]:
print shape(a)
In [8]:
print a.shape
由上可知,list只支持len(), 该方法实际是调用了对象的__len__(self)方法
In [12]:
print len(b)
print b.size
print b.shape
对比之下,numpy.array同时支持len, size, shape, 注意看三者返回值的区别。
此外,numpy中还提供matrix的数据类型,具体请看:
In [17]:
c = np.mat(a)
print type(c)
print c
d = np.mat(b)
print type(d)
print d
print len(d)
print d.size
print d.shape
从上面的例子可以看出,martix支持由list和numpy.array创建,同时支持len, size以及shape. 另外从numpy.matrix上可以了解到,matrix相对于list和numpy.array而言,支持*(矩阵相乘),**(矩阵幂)等。
In [20]:
print c*d.T
补充:numpy中有一个numpy.shape()函数,支持array_like如list, array等,返回tuple of ints, 具体可查看其帮助函数。
</div>