python中二维数组的初始化——关于python中的深浅拷贝问题

  • Post author:
  • Post category:python


借鉴

原文链接

的内容:

方法1 直接定义

matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

方法2 间接定义

matrix = [[0 for i in range(3)] for i in range(3)]

方法3

matrix = []
for i in range(3):
    matrix.append([0] * 3)

可以解决浅拷贝的问题

引发浅拷贝的现象(注意:以下行为会使列表产生奇怪的特性)

base = [0] * 3
matrix = []
for i in range(3):
    matrix.append(base)
print(matrix)
matrix[1][1] = 2
print(matrix)

结果:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 2, 0], [0, 2, 0], [0, 2, 0]]

说明matrix中三个[0, 0, 0]都是base的映射,改一个,base就被改了,然后三个元素全改了。

——————————-2020.3.21———————————–

关于含有列表的列表的处理也有深浅拷贝问题,例如以下代码片段:

    def addCurrentShapeToShapes(self):
        if len(self.current_shape[1][0]) > 0:
            print(self.current_shape, self.shapes)
            self.shapes.append(self.current_shape)
            print(self.shapes)
            self.current_shape[1][0].clear()
            self.current_shape[1][1].clear()
            print(self.shapes)

结果:

[‘rect’, [[105, 306], [67, 341]]] []

[[‘rect’, [[105, 306], [67, 341]]]]

[[‘rect’, [[], []]]]

造成应用程序的bug,解决方法是要进行深拷贝,可以self.shapes.append(copy.deepcopy(self.current_shape))来解决

参考链接


Python List 列表的深浅层复制



版权声明:本文为z1314520cz原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。