python中的數組和列表


####轉自: 

#環境win64+anaconda+python3.6

list & array

(1)list不具有array的全部屬性(如維度、轉置等)

代碼1:

 
#eg1_1
 
import numpy as np
 
a = np.array([[1,2,0,1],[1,6,9,55],[7,8,9,5]])#a為數組
 
print(a.T)
 
 
 
#Result:
 
[[ 1  1  7]
 
 [ 2  6  8]
 
 [ 0  9  9]
 
 [ 1 55  5]]
 
 
 
#eg1_2
 
a = [[1,2,0,1],[1,6,9,55],[7,8,9,5]] #a為列表
 
print(a.T)
 
 
 
#Result:
 
'list' object has no attribute 'T'

 

 

代碼2:

 
#eg1_3
 
import numpy as np
 
a=np.array([[1,2,3],[1,1,4],[1,5,1]])
 
print(a.shape)
 
 
 
#Result:
 
(3, 3)
 
 
 
#eg1_4
 
a=[[1,2,3],[1,1,4],[1,5,1]]
 
print(a.shape)
 
 
 
#Result
 
'list' object has no attribute 'shape'

 

 

(順帶一提,如何把一個數組轉化為列向量:↓)

 
import numpy as np
 
a=np.array([[1,2,3],[1,1,4],[1,5,1]])
 
a=a.reshape(-1,1)
 
print(a)
 
 
 
#Result:
 
[[1]
 
[2]
 
[3]
 
[1]
 
[1]
 
[4]
 
[1]
 
[5]
 
[1]]

 

(2)a[:m]的含義,a可以是列表或者數組,但是無論是哪種情況,a[:0]為空

 
#eg2_1
import numpy as np
a=np.array([[4,1,2],
[7,4,10],
[12,17,88]])
#a=np.array([(4,1,2),
# (7,4,10),
# (12,17,88)]) 這兩個a中[和(不一樣,其實它們完全一樣
print(a[:0])
print(a[:1])
print(a[:2])
#Result:
[]
[[4 1 2]]
[[ 4 1 2]
[ 7 4 10]]
#eg2_1
a=[(4,1,2),(7,4,10),(12,17,88)]
print(a[:0])
print(a[:1])
print(a[:2])
#Result:
[]
[(4, 1, 2)]
[(4, 1, 2), (7, 4, 10)]

 

(3)array和list關於“==”的計算

 
#eg3_1
 
import numpy as np
 
a=np.array(['dog','cat','car'])
 
b=np.array(['dog','cat','trunk'])
 
acc = (np.mean(a == b))
 
print(acc)
 
 
 
#Result
 
0.6666666666666666
 
 
 
#eg3_2
 
import numpy as np
 
a=['dog','cat','car']
 
b=['dog','cat','trunk']
 
acc = (np.mean(a == b))
 
print(acc)
 
 
 
#Result
 
0.0

 

(4)array和list關於“*”的計算

 
from numpy import *
 
#a為數組
 
a=array([[1,2,3],
 
[4,5,6]])
 
b=4*a
 
print(b)
 
 
 
[[ 4 8 12]
 
[16 20 24]]
 
 
 
 
 
from numpy import *
 
#a為列表
 
a=([[1,2,3],
 
[4,5,6]])
 
b=4*a
 
print(b)
 
 
 
[[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]]

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM