[英]python multi-dimension list: cannot store values correctly
我遇到了一個非常奇怪的問題。 我使用多維列表來存儲一些數據。 數據在.txt文件中,每行有9位數字,並且有450行數據。 對於每9行數據(9x9數字網格),我想將它們分組為子列表。 我使用下面的代碼存儲數據,但問題是當我完成並打印多維列表時,列表中的每一行數據似乎都是相同的。 對不起,我的描述很抱歉,也許我的代碼可以告訴所有問題,請告訴我代碼有什么問題。 我在Windows上使用python 2.7.5,謝謝。
# grid is a 3-dimension list, the first dimension is the index of 9x9 digit subgrid
# there are 50 9x9 digit subgrid in total.
grid = [[[0]*9]*9]*50
with open('E:\\sudoku.txt', 'r') as f:
lines = f.readlines()
for line_number, line in enumerate(lines, 1):
# omit this line, it is not data
if line_number % 10 == 1:
continue
else:
for col, digit in enumerate(line[:-1]):
if line_number % 10 == 0:
x = line_number / 10 - 1
y = 8
else:
x = line_number / 10
y = line_number % 10 - 2
grid[x][y][col] = int(digit)
# I print all the digits in the list and compare them with the .txt file
# it shows every single cell in grid are set correctly !!
print 'x=%d, y=%d, z=%d, value=%d '% (x, y, col, grid[x][y][col])
# But strange thing happens here
# I only get same line of value, like this:
# [[[0, 0, 0, 0, 0, 8, 0, 0, 6], [0, 0, 0, 0, 0, 8, 0, 0, 6] ... all the same line
# and 000008006 happens to be the last line of data in the .txt file
# what happens to the rest of data ? It's like they are all overwritten by the last line
print grid
列表乘法不會克隆(或創建新的)對象,而只是多次引用同一(在您的情況下是可變的)對象。
看這里:
a = [[3]*3]*3
print(a)
a[0][1] = 1
print(a)
grid = [[[0]*9]*9]*50
不會創建50個9x9網格。 當您聲明[[[0]*9]*9]*50
,python將創建9引用[0]
。
列表乘法只會創建同一對象的新引用,換句話說,您創建的每個列表都引用內存中用於存儲[0]
列表的相同位置。
一個類似的問題 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.