python中的list是python的內(nèi)置數(shù)據(jù)類型,list中的數(shù)據(jù)類不必相同的,而array的中的類型必須全部相同。在list中的數(shù)據(jù)類型保存的是數(shù)據(jù)的存放的地址,簡單的說就是指針,并非數(shù)據(jù),這樣保存一個(gè)list就太麻煩了,例如list1=[1,2,3,'a']需要4個(gè)指針和四個(gè)數(shù)據(jù),增加了存儲和消耗cpu。
numpy中封裝的array有很強(qiáng)大的功能,里面存放的都是相同的數(shù)據(jù)類型
list1=[1,2,3,'a'] print list1 a=np.array([1,2,3,4,5]) b=np.array([[1,2,3],[4,5,6]]) c=list(a) # array到list的轉(zhuǎn)換 print a,np.shape(a) print b,np.shape(b) print c,np.shape(c)
運(yùn)行結(jié)果:
[1, 2, 3, 'a'] # 元素?cái)?shù)據(jù)類型不同,并且用逗號隔開 [1 2 3 4 5] (5L,) # 一維數(shù)組,類型用tuple表示 [[1 2 3] [4 5 6]] (2L, 3L) [1, 2, 3, 4, 5] (5L,)
創(chuàng)建:
array的創(chuàng)建:參數(shù)既可以是list,也可以是元組.使用對應(yīng)的屬性shape直接得到形狀
a=np.array((1,2,3,4,5))# 參數(shù)是元組 b=np.array([6,7,8,9,0])# 參數(shù)是list c=np.array([[1,2,3],[4,5,6]])# 參數(shù)二維數(shù)組 print a,b, c.shape()
也可以直接改變屬性array的形狀,-1代表的是自己推算。這里并不是T, reshape(())也可以
c = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]]) c.shape # (3L, 4L) c.shape=4,-1 //c.reshape((2,-1)) c <pre style="box-sizing: border-box; overflow: auto; font-size: 14px; padding: 0px; margin-top: 0px; margin-bottom: 0px; line-height: 17.0001px; word-break: break-all; word-wrap: break-word; border: 0px; border-radius: 0px; white-space: pre-wrap; vertical-align: baseline; background-color: rgb(255, 255, 255);">array([[ 1, 2, 3], [ 4, 4, 5], [ 6, 7, 7], [ 8, 9, 10]])
這里的reshape最終相當(dāng)于是一個(gè)淺拷貝,也就是說還是和原來的書c使用相同的內(nèi)存空間
d=c.reshape((2,-1)) d[1:2]=100 c array([[ 1, 2, 3], [ 4, 4, 5], [100, 100, 100], [100, 100, 100]])
前面在創(chuàng)建數(shù)組的時(shí)候并沒有使用數(shù)據(jù)類型,這里我們也可以使用數(shù)據(jù)類型。默認(rèn)的是int32.
a1=np.array([[1,2,3],[4,5,6]],dtype=np.float64) print a1.dtype,a.dtype #float64 int32<pre style="margin-top: 0px; margin-bottom: 0px; line-height: 17.0001px; box-sizing: border-box; overflow: auto; font-size: 14px; padding: 0px; word-break: break-all; word-wrap: break-word; border: 0px; border-radius: 0px; white-space: pre-wrap; vertical-align: baseline; background-color: rgb(255, 255, 255);">
前面在創(chuàng)建的時(shí)候我們都是使用的np.array()方法從tuple或者list轉(zhuǎn)換成為array,感覺很是費(fèi)勁,numpy自己提供了很多的方法讓我們自己直接創(chuàng)建一個(gè)array.
新聞熱點(diǎn)
疑難解答
圖片精選