首頁 > 軟體

Python中的二維列表使用及說明

2022-12-21 14:00:33

一、概念

二維列表的元素還是列表(列表的巢狀),稱之為二維列表。

需要通過行標和列標來存取二維列表的元素

二、建立二維列表

1、追加一維列標來生成二維列標

生成一個4行3列的二維列表

row1 = [3, 4, 5]
row2 = [1, 5, 9]
row3 = [2, 5, 8]
row4 = [7, 8, 9]
matrix = []
matrix.append(row1)
matrix.append(row2)
matrix.append(row3)
matrix.append(row4)
print(matrix)

輸出結果:

[[3, 4, 5], [1, 5, 9], [2, 5, 8], [7, 8, 9]]

2、直接賦值生成二維列表

定義一個3行4列的二維列表

matrix = [[], [], []]
matrix[0] = [3, 4, 5, 6]
matrix[1] = [8, 7, 9, 5]
matrix[2] = [0, 2, 5, 8]
print(matrix)

輸出結果:

[[3, 4, 5, 6], [8, 7, 9, 5], [0, 2, 5, 8]]

三、一維列標與二維列表的轉換

1、一維列表轉換成二維列表

將1到24的全部數位按順序放到一個4行6列的二維列表裡

# 將1到24的全部數位按順序放到一個4行6列的二維列表裡
nums = []
for i in range(1, 25):
    nums.append(i)

martix = []
for k in range(4):
    row = []
    for j in range(1, 7):
        row.append(j + 6 * k)
    martix.append(row)

for arr in martix:
    print(arr)

輸出結果:

[1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12]
[13, 14, 15, 16, 17, 18]
[19, 20, 21, 22, 23, 24]

2、二維列表轉換成一維列表

將一個3行5列的二維列表扁平化一維列表

# 將一個3行5列的二維列表扁平化一維列表
nums = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
arr = []
for i in nums:
    for j in i:
        arr.append(j)
print(arr)

輸出結果:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

3、利用NumPy實現陣列的變維操作

利用NumPy陣列提供的 reshape(m, n) 實現陣列的變維

(1)一維陣列變成二維陣列

In [31]:import numpy as np

In [32]:arr1 = np.arange(1,25)  # arange() 建立一個等差陣列

In [33]:arr2 = arr1.reshape(4, 6)  # reshape()一維轉二維

In [34]:arr2
Out[34]: 
array([[ 1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12],
       [13, 14, 15, 16, 17, 18],
       [19, 20, 21, 22, 23, 24]])

In [35]:arr2 = arr1.reshape(3, 8)

In [36]:arr2
Out[36]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16],
       [17, 18, 19, 20, 21, 22, 23, 24]]) 

(2)二維陣列轉換成一維陣列

In [36]:arr2
Out[36]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16],
       [17, 18, 19, 20, 21, 22, 23, 24]])

In [37]:arr1 = arr2.reshape(1, 24)[0]

In [38]:arr1
Out[38]: 
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24])

四、存取二維列表

通過行標與列標來存取二維列表(可以通過切片運算存取行)

1、存取行

In [36]:arr2
Out[36]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16],
       [17, 18, 19, 20, 21, 22, 23, 24]])

In [39]:arr2[1]
Out[39]: array([ 9, 10, 11, 12, 13, 14, 15, 16])

2、存取元素

In [40]:arr2
Out[40]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16],
       [17, 18, 19, 20, 21, 22, 23, 24]])

In [41]:arr2[1][2]  # 第2行第3列
Out[41]: 11

3、NumPy二維陣列的存取

In [42]:import numpy as np

In [43]:arr2
Out[43]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16],
       [17, 18, 19, 20, 21, 22, 23, 24]])

In [44]:arr2[1]  # 存取行
Out[44]: array([ 9, 10, 11, 12, 13, 14, 15, 16])

In [45]:arr2[:, 0]  # 存取列
Out[45]: array([ 1,  9, 17])

In [46]:arr2[2, 3]  # 存取元素
Out[46]: 20

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com