如何将列表变量赋予两个 class 变量?

How to give a list variable to two class variable?

我用 "copy" 得到两个 class 变量。但是当后一个函数修改两个变量之一的值时,另一个变量也会发生变化。如何生成两个自变量?

无法导入numpy等其他包解决。 谢谢大家。

Leetcode第200题,岛屿数量

input_list = [  [0, 1, 1, 1, 0],
                [0, 1, 0, 1, 1], 
                [1, 1, 0, 0, 1], 
                [0, 0, 1, 0, 1]]

class Solution():
    def __init__(self, input_list_ori):
        self.island_count = 0
        self.input_list = input_list_ori.copy()
        # self.input_list_ori = [[0 for j in range(len(self.input_list[0]))]for i in range(len(self.input_list))]
        self.input_list_ori = self.input_list.copy()
        self.dirs = [[-1, 0], [0, 1], [0, -1], [1, 0]]

    def find_connect_one(self):
        assert(len(self.input_list) > 0)
        for i_row in range(len(self.input_list[0])):
            for i_col in range(len(self.input_list)):
                if self.input_list[i_row][i_col] == 1:
                    self.island_count += 1
                    self.dfs(i_row, i_col)
        return self.island_count, self.input_list_ori

    def dfs(self, i_row, i_col):
        self.input_list[i_row][i_col] = 0
        self.input_list_ori[i_row][i_col] = self.island_count

        for dir in self.dirs:
            new_i_row = i_row+dir[0]
            new_i_col = i_col+dir[1]
            if new_i_row >= 0 and new_i_col >= 0 and new_i_row < len(self.input_list) and new_i_col < len(self.input_list[0]):
                if self.input_list[new_i_row][new_i_col] == 1:
                    self.dfs(new_i_row, new_i_col)

solution = Solution(input_list)
print(len(input_list))
island_count, input_list_ori = solution.find_connect_one()
print(island_count)

def dfs(self, i_row, i_col):
    self.input_list[i_row][i_col] = 0
    self.input_list_ori[i_row][i_col] = self.island_count

我希望在这两个列表中得到不同的值。虽然我是用"copy"运算符生成的,但它们总是相互影响的。

你应该使用 copy.deepcopy.

来自 documentation 的更多解释:

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

您的副本正在参考内部列表创建新列表。因此,当您修改内部列表时,两个列表都有 self.input_listself.input_list_ori.