[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
博主在面对Python中矩阵维度问题时经常晕头转向,不知道怎么一眼看出是几维矩阵,往往得通过笨办法:shape函数来取出来看,但是假设shape函数返回维度(6,2,3),也不知道这些数组分别代表了什么意思,今天特意写一下博客记录一下。
如何看出是几维数组?
首先给出如下函数:
a = np.random.randint(10,size=(3,4)) print(a)
打印出来的结果是:
很明显,我给出的是两维的,3行4列的一个矩阵。如何判断是几维的,就看最外层的有几个中括号,有几个中括号就是几维的,很明显有两个中括号就是2维的。因为
size=(3,4),秉着行在前,列在后的原则,所以是3行4列。
继续看这个函数:
a = np.random.randint(10,size=(2,3,4)) print(a)
打印出来的结果是:
按照刚刚的经验,看这个打印出来的结果,首先分析这是一个3维的矩阵(因为最外层有3个中括号)。然后再去找两个中括号括起来的数据,
看两个中括号括起来的数据,是一个3行4列的,意味着size=(x, 3, 4),其实就是相当于找最内层的二维矩阵,这个二维矩阵表示时是靠右的,
然后发现有两个2维矩阵,所以size=(2,3,4)
继续看这个函数:
a = np.random.randint(10,size=(4,3,6)) print(a)
打印出来的结果是:
首先确定这个是3维的,其中2维是3行6列,总共有4个2维,因此size就是(4,3,6)
为了举一反三,再看一个:
a = np.random.randint(10,size=(3,2,2,6)) print(a)
输出结果:
很明显这是一个4维的矩阵,size=(X,X,X,X);最右边的XX(即2维)是2行6列,那么
每个外层维度(3维)内总共有几个2行6列呢(每个三维内总共有几个二维),有2个;每个4维内总共有几个3维呢,有3个,所以size就是(3,2,2,6)
如何使用shape函数?
用眼睛观察是比较直接的一种方法,不过保不齐会出错,shape函数可以很方便的看出有多少维度。但是shape函数有两种用法
np.shape(array) array.shape
一种是将数组放进shape函数内,另一种是将shape用作一种属性,用.shape 这两种方法有啥区别呢?
一、如果我们想看一个数组有多少维度,那么上述两种方法都行
二、如果我们想看数组第二维、第n维是多少,那么只能用 array.shape[2] (第三维是多少)
三、如果我们想看第4维的长宽高是多少,用 np.shape(array[2]) 假设size=(3,2,2,6),则返回结果是(2,2,6)
但这种一般没啥用
综上,一般直接用 .shape 就行
要补充一下,常见的既可以作为函数,又可以作为属性的,还要size,例如
array.size np.size(array)
如果看数组里有多少个元素,那么这两个方法都可以