python中list 和array的區別

python中 list 與數組的互相轉換

(1)list轉array:         np.array(a)

(2)array 轉list           a.tolist()

    輸出結果: 

list.append()

list.pop()

list.index()

list.count()

list.remove(obj)  

len(list)

list.sort


ndarray.shape 輸出一個元組

t2 = np.array([[1, 2, 3], [4, 5, 6]]) # 二維數組

print(t2.shape)     #輸出元組(2, 3) 

  • print(x.shape[0]) # 2 只輸出行數
  • print (x.shape[1]) # 3

print(len(t2))        #2 輸出行數

print(len(t2[0]))    #3 輸出列數

ndarray.size 

     輸出數組元素的總個數,等於shape屬性中元組元素的乘積。

ndarray.reshape數組變形


t3 = np.arange(12)
t4 = t3.reshape((3, 4))   # 改變形狀,改成3行4列
print(t4)
'''
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

np.where(條件)

      返回的是元組,每個元組中的元素是array數組.   np.where()並不接受list類型的參數
—— np.where()[0] 表示行的索引;
—— np.where()[1] 則表示列的索引;

>>> a = np.arange(27).reshape(3,3,3)
>>> a
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

>>> np.where(a > 5)
(array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2]),
 array([2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2]),
 array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]))


# 符合條件的元素爲
       [ 6,  7,  8]],

      [[ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17]],

      [[18, 19, 20],
       [21, 22, 23],
       [24, 25, 26]]]

所以np.where會輸出每個元素的對應的座標,因爲原數組有三維,所以tuple中有三個數組。

實例:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章