为什么我的列表只在循环后保留最后一行?

时间:2018-01-31 02:25:43

标签: python

def main():
    row = 5
    col = 3
    count = 0
    board = list([[""]*col]*row)
    for i in range(0,row):
        for n in range(0,col):
            board[i][n] = str(count)
            print board[i][n] , count, i, n
            count+=1

    print board
main()

当我运行此代码时,我希望我的列表是:

[[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14]]

当我在循环中打印单个索引时,它会正确分配,但在退出循环后,我很好地将输出结束为

[[12,13,14],[12,13,14],[12,13,14],[12,13,14],[12,13,14]]

1 个答案:

答案 0 :(得分:0)

尝试替换此行

board = list([[""]*col]*row)

board = [[0 for x in range(col)] for y in range(row)]

此更改使代码适用于我。