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]