私は非常に奇妙な問題に遭遇しました。多次元リストを使用してデータを保存します。データは .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