国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python 中的list和array的不同之處及轉(zhuǎn)換問題

2020-02-22 23:26:57
字體:
供稿:網(wǎng)友

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.

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 防城港市| 丰原市| 长治市| 康马县| 新蔡县| 海南省| 沅江市| 达州市| 景洪市| 措勤县| 海原县| 泽普县| 宁远县| 孙吴县| 西丰县| 华池县| 永顺县| 大兴区| 余庆县| 安庆市| 荔浦县| 区。| 哈尔滨市| 大丰市| 田阳县| 巴东县| 德钦县| 措美县| 凤凰县| 缙云县| 准格尔旗| 桦川县| 福海县| 惠州市| 临沭县| 南宫市| 三门县| 克什克腾旗| 安乡县| 会昌县| 南昌县|