更改2D字符列表中的元素

时间:2018-12-09 12:21:39

标签: python python-3.x list char

我想访问和更改2D字符列表中的单个字符。但是,当我更改一个时,它将更改整个列。为什么是这样?我究竟做错了什么?在第31行:我正在修改数组中的一个元素,并且得到的结果不同于我想要和期望的结果。

下面是我的代码:

from random import *

class chessBoard:

    BOARD       = None
    BOARD_WIDTH = 8

    def __init__(self,W = 8):
       self.BOARD = []
       self.BOARD_WIDTH = W

       aRow = ['.'] * self.BOARD_WIDTH
       for curRow in range(self.BOARD_WIDTH):
           self.BOARD.append(aRow)


    def printBoard(self):
       for curRow in self.BOARD:
          print(curRow)


    def initialiseRandomQ(self,N):

       cords = []
       for ii in range(self.BOARD_WIDTH):
          for jj in range(self.BOARD_WIDTH):
              cords.append( [ii,jj] )

       shuffle(cords)

       self.BOARD[0][0] = '1'

       # for curQ in range(N):
       #     xx = cords[curQ][0]
       #     yy = cords[curQ][1]

       #     print(xx,yy)
       #     print(cords[curQ]) 

       #     self.BOARD[xx][yy] = 'Q'

#PROGRAM START#

N_QUEENS    = 2

myChessBoard = chessBoard()

myChessBoard.initialiseRandomQ(2)

myChessBoard.printBoard()

1 个答案:

答案 0 :(得分:1)

此:

class chessBoard:

    BOARD       = None
    BOARD_WIDTH = 8

    def __init__(self,W = 8):
       self.BOARD = []
       self.BOARD_WIDTH = W

       aRow = ['.'] * self.BOARD_WIDTH      # this is one list, it's a reference to data
       for curRow in range(self.BOARD_WIDTH):
           self.BOARD.append(aRow)          # adds the same reference 8 times

您的列表包含8次相同的参考,如果您通过一个参考更改数据,则其他(相同)的数据也会反映出来。所有引用都指向相同的数据。

使用

           self.BOARD.append(['.'] * self.BOARD_WIDTH) # add "unique" lists instead

您可以检查id()

# your version ( self.BOARD.append(aRow) )
print(list(map(id,myChessBoard.BOARD))) 

[140415825494600, 140415825494600, 140415825494600, 140415825494600,
 140415825494600, 140415825494600, 140415825494600, 140415825494600]

# fixed version (self.BOARD.append(['.'] * self.BOARD_WIDTH))
[140560309994568, 140560309994440, 140560309994376, 140560309994312, 
 140560309994248, 140560309994184, 140560309994120, 140560309994696]

请参见What is the id( ) function used for?