首页 > 解决方案 > 通过从内存中删除旧内容来更新表的最有效方法是什么?

问题描述

我有以下代码:

class MyClass:

    def __init__(self):
        self.w = 2
        self.h = 2
        self.table = []

    def add_item(self, x, y, string_value):

        table0 = self.table
        if x >= self.w:
            self.w = x + 1
        if y >= self.h:
            self.h = y + 1

        self.table = [['foo' for h in range(self.h)] for w in range(self.w)]
        for i in range(0, len(table0)):
            for j in range(0, len(table0[i])):
                self.table[i][j] = table0[i][j]

        self.table[x][y] = string_value


def main():
    c = MyClass()
    c.add_item(7, 0, 'May')
    c.add_item(0, 5, 'June')
    c.add_item(2, 3, 'January')


if __name__ == "__main__":
    main()

此代码从用户那里获取坐标,以将具有特定值的单元格添加到表中。为此,如果坐标大于当前表格的尺寸,则表格的尺寸将相应更新。我有两个问题:

  1. add_item函数中有一个嵌套循环,用于将之前的内容复制到更新后的表中。就时间复杂度而言,没有更有效的方法吗?
  2. 每次更新表格时,之前的内容仍然在内存中,没有分配给任何变量,那我该如何摆脱呢?我知道python中有Garbage Collector接口,但我以前从未使用过,如果这是正确的方法,我该如何使用它?

谢谢。

标签: pythonpython-3.x

解决方案


最好不要每次都重新创建列表。查看此版本:仅动态创建所需的单元格,而保留现有的单元格:

class MyClass:

    def __init__(self):
        self.w = 0
        self.h = 0
        self.table = []

    def add_item(self, x, y, string_value):

        while y >= self.h:
            for xx in range(self.w):
                self.table[xx].append(None)
            self.h = self.h + 1
          
        while x >= self.w:
            self.table.append([None] * self.h)
            self.w = self.w + 1
        
        self.table[x][y] = string_value


def main():
    c = MyClass()
    c.add_item(7, 0, 'May')
    c.add_item(0, 5, 'June')
    c.add_item(2, 3, 'January')
    print(c.table) #=>[[None, None, None, None, None, 'June'], [None, None, None, None, None, None], [None, None, None, 'January', None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None], ['May', None, None, None, None, None]]

if __name__ == "__main__":
    main()

另请注意,垃圾收集器是自动完成其工作的东西。通常你不必担心它。


推荐阅读