【參考資料】
https://blog.csdn.net/qq_28618765/article/details/78081959
shape函數(shù)是numpy.core.fromnumeric中的函數(shù),它的功能是讀取矩陣的長度,比如shape[0]就是讀取矩陣第一維度的長度。
shape的輸入?yún)?shù)可以是一個整數(shù)(表示維度),也可以是一個矩陣。
- 參數(shù)是一個數(shù)時,返回空:
>>> import numpy as np
>>> np.shape(0)
()
- 參數(shù)是一維矩陣:
>>> import numpy as np
>>> np.shape([1])
(1,)
>>> np.shape([1, 2])
(2,)
- 參數(shù)是二維矩陣:
>>> import numpy as np
>>> np.shape([[1],[2]])
(2, 1)
>>> np.shape([[1, 2], [2, 3], [3, 4]])
(3, 2)
- 直接用.shape可以快速讀取矩陣的形狀,使用shape[0]讀取矩陣第一維度的長度
>>> import numpy as np
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> a.shape
(3, 3)
>>> a.shape[0]
3
>>> a.shape[1]
3
- 但是當某一維度長度不一致時,讀取所有維度時則不能讀出長短不一致的維度
>>> import numpy as np
>>> a = np.array([[1, 2, 3], [4, 5], ])
>>> a.shape
>>> a.shape[0]
2
>>> a.shape[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
(2,)