简体   繁体   English

python多维列表:无法正确存储值

[英]python multi-dimension list: cannot store values correctly

I have met a very strange issue. 我遇到了一个非常奇怪的问题。 I use a multi-dimension list to store some data. 我使用多维列表来存储一些数据。 The data are in a .txt file, every line has 9 digit, and it has 450 lines data. 数据在.txt文件中,每行有9位数字,并且有450行数据。 For every 9 lines data(a 9x9 digit grid), I want to group them as a sublist. 对于每9行数据(9x9数字网格),我想将它们分组为子列表。 I use the code below to store the data, and my problem is when I finished and print the multi-dimension list, it seems every line of data in the list are the same. 我使用下面的代码存储数据,但问题是当我完成并打印多维列表时,列表中的每一行数据似乎都是相同的。 Sorry for my poor description, maybe my code can tell everything, and please tell me what's wrong with the code. 对不起,我的描述很抱歉,也许我的代码可以告诉所有问题,请告诉我代码有什么问题。 I use python 2.7.5 on Windows, thanks. 我在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

The list multiplication does not clone (or create new) objects, but simply references the same (in your case mutable) object various times. 列表乘法不会克隆(或创建新的)对象,而只是多次引用同一(在您的情况下是可变的)对象。

See here: 看这里:

a = [[3]*3]*3
print(a)
a[0][1] = 1
print(a)

grid = [[[0]*9]*9]*50 does not create 50 of 9x9 grid. grid = [[[0]*9]*9]*50不会创建50个9x9网格。 When you state [[[0]*9]*9]*50 , python creates 9 reference of [0] . 当您声明[[[0]*9]*9]*50 ,python将创建9引用[0]

List multiplication only creates new references of the same object, in other words, every single list you made refer to the same place in the memory, used to store the [0] list. 列表乘法只会创建同一对象的新引用,换句话说,您创建的每个列表都引用内存中用于存储[0]列表的相同位置。

A similiar question . 一个类似的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM