简体   繁体   English

Python 中列表的奇怪行为

[英]Strange behavior with lists in Python

I have noticed that probability_matrix seems to become adapted_given_board despite never being assigned it.我注意到probability_matrix似乎变成adapted_given_board ,尽管它从未被分配过。

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.也就是说,您正在为self.probability_matrix创建一个新名称,而不是一个包含内容副本的新列表。

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;尝试使用copy来解决此问题时要小心,因为您正在使用二维列表; 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:有这样的东西deepcopy ,但这里有一个非常小的修复的想法,它只是在分配给矩阵之前分配矩阵中的新条目:

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...或者您可以简单地 append 您的新元素,而不是按索引分配它们......

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)

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

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