shape函数返回list,array,matrix等的一维和二维长度值。
1)list列表
列表只有一维,二维为0
>>> a = [1,2,3]
>>> np.shape(a)
(3,)
上面是一维列表,长度是3
值得注意的是,列表是没有shape函数的,如下:
>>> a.shape[0]
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
a.shape[0]
AttributeError: 'list' object has no attribute 'shape'
2)array数组
>>> a = np.eye(4,3)
>>> a
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 0., 0., 0.]])
>>> np.shape(a)
(4, 3)
>>> a.shape[0]
4
>>> a.shape[1]
3
>>>
上面建立了一个4x3的数组,第一个维度是4(即第一个中括号里面的列表数量),第二个维度是3
3)matrix
>>> b = mat([[1,2,3],[2,3,5]])
>>> b
matrix([[1, 2, 3],
[2, 3, 5]])
>>> np.shape(b)
(2, 3)
>>>
本文介绍了Python中shape函数的应用,包括对list、array及matrix等不同数据结构一维和二维长度值的获取方法。详细展示了如何使用numpy库处理这些数据类型,并解释了shape属性的具体含义。
6762

被折叠的 条评论
为什么被折叠?



