Python - 正確使用方法的 2D 陣列/列表


Python 提供了許多建立二維列表/陣列的方法。但是,必須瞭解這些方法之間的區別,因為它們可能會在程式碼中產生複雜性,而這些複雜性可能非常難以辨別。

示例

 實際演示

rows, cols = (5, 5)
arr = [[0]*cols]*rows
#lets change the first element of the 1st row to 1 & print the array
arr[0][0] = 1
for row in arr:
   print(row)
arr = [[0 for i in range(cols)] for j in range(rows)]
#again in this new array lets change the 1st element of the first row
# to 1 and print the array
arr[0][0] = 1
for row in arr:
   print(row)

輸出

[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

更新於: 06-Aug-2020

131 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告