简体   繁体   中英

Strange behavior with lists in Python

I have noticed that probability_matrix seems to become adapted_given_board despite never being assigned it.

def build_probability_matrix(self):
    r = 0
    p = -1
    adapted_given_board = self.probability_matrix
    print(self.game.board.given_board)
    for i in range(len(self.game.board.given_board)-1):
        p += 1
        if self.game.board.given_board[i] == '\n':
            r += 1
            p = -1
        else:
            adapted_given_board[r][p] = self.game.board.given_board[i]
    print(adapted_given_board)

This assignment:

adapted_given_board = self.probability_matrix

is a reference, not a copy. That is, you're creating a new name for self.probability_matrix , not a new list that has a copy of the contents.

So when you do:

adapted_given_board[r][p] = self.game.board.given_board[i]

it's the exact same as if you'd done:

self.probability_matrix[r][p] = self.game.board.given_board[i]

Be careful about trying to use copy to fix this, since you're working with two-dimensional lists; you might end up just pushing the problem down one level. There is such a thing as deepcopy , but here's one idea for a very minimal fix that just allocates new entries in the matrix before you assign to them:

def build_probability_matrix(self):
    r = 0
    p = -1
    adapted_given_board = [[]]  # start with one row that has zero cells
    print(self.game.board.given_board)
    for i in range(len(self.game.board.given_board)-1):
        p += 1
        adapted_given_board[r].append(None)  # add a cell
        if self.game.board.given_board[i] == '\n':
            r += 1
            adapted_given_board.append([])   # add a row
            p = -1
        else:
            adapted_given_board[r][p] = self.game.board.given_board[i]
    print(adapted_given_board)

Or you could simply append your new elements rather than assigning them by index...

def build_probability_matrix(self):
    adapted_given_board = [[]]        
    print(self.game.board.given_board)
    for element in self.game.board.given_board:
        if element == '\n':
            adapted_given_board.append([])
        else:
            adapted_given_board[-1].append(element)
    print(adapted_given_board)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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