Python 中的列表或字典在内存和速度方面哪个更昂贵

Which is more expensive in terms of memory and speed Lists or dictionaries in Python

我正在我的计算机上测试记忆代码。我有范围为 100000 的数组。使用以下代码。

def fact1(n):
   if n<1:
      return 1
   else:
      fa=1
      for i in range(1, n+1):
          fa*=i
      return fa

使用记忆技术,下面的代码是,

  memolookuptable={1:1, 2:2}
  def fact2(n):
      if n not in memoookuptable.keys():
          for i in range(3,n+1):
              if i not in memoookuptable.keys():
                   memolookuptable[i]=i*memolookuptable[i-1]

根据我对代码的理解,通过内存优化的记忆以低速启动 运行。我是否将记忆正确理解为通过存储计算值来避免重新计算?如果这是正确的,为什么尽管计算值很容易获得,但较大的计算速度会变慢?

使用记忆优化内存和速度的最佳方法是什么?

您无需调用 .keys() - 您只需使用 if n not in memolookuptable:。我相信这应该更快,因为它使用散列。 .keys() returns 一个列表,查找速度较慢。