Python中数组及矩阵的⼤⼩
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
<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>()
python获取数组长度
----> 1 print a.size
AttributeError: '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.shape
AttributeError: 'list' object has no attribute 'shape'
由上可知,list只⽀持len(), 该⽅法实际是调⽤了对象的__len__(self)⽅法
In [12]:
print len(b)
print b.size
print b.shape
3
12
(3, 4)
对⽐之下,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
<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]]
3
12
(3, 4)
从上⾯的例⼦可以看出,martix⽀持由list和numpy.array创建,同时⽀持len, size以及shape. 另外从上可以了解到,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, 具体可查看其帮助函数。        </div>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。