python - 通过从内存中删除旧内容来更新表的最有效方法是什么?
问题描述
我有以下代码:
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()
此代码从用户那里获取坐标,以将具有特定值的单元格添加到表中。为此,如果坐标大于当前表格的尺寸,则表格的尺寸将相应更新。我有两个问题:
- add_item函数中有一个嵌套循环,用于将之前的内容复制到更新后的表中。就时间复杂度而言,没有更有效的方法吗?
- 每次更新表格时,之前的内容仍然在内存中,没有分配给任何变量,那我该如何摆脱呢?我知道python中有Garbage Collector接口,但我以前从未使用过,如果这是正确的方法,我该如何使用它?
谢谢。
解决方案
最好不要每次都重新创建列表。查看此版本:仅动态创建所需的单元格,而保留现有的单元格:
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()
另请注意,垃圾收集器是自动完成其工作的东西。通常你不必担心它。
推荐阅读
- php - 将月份名称格式化为当地语言
- javascript - 如何使用赛普拉斯测试网页已禁用滚动?
- html - 无论屏幕大小如何,在元素上保持相对于其他元素的相同位置
- javascript - 数组过滤方法中的for循环
- c# - 从脚本更改 ReorderableList 最大项目
- java - 如何在多个结构中获取链接和java中的元素
- macos - 无法增加堆大小 IntelliJ Mac – 更改了 idea.vmoptions+restarted
- spring - tomcat 9.0.43 上的 SQL DB 会话泄漏问题
- questdb - 如何防止意外删除 QuestDB 中的记录?
- parameter-passing - 将参数从功能文件传递到另一个功能文件