2010-01-06 28 views
-2

我的代碼複製 'memoize的' 功能:爲什麼我的代碼錯誤?我在django.utils.functional

a=[1,2,3,4] 
b=a[:2] 
c=[] 
c[b]='sss'#error 

memoize的功能:

def memoize(func, cache, num_args): 
    def wrapper(*args): 
     mem_args = args[:num_args]#<------this 
     if mem_args in cache: 
      return cache[mem_args] 
     result = func(*args) 
     cache[mem_args] = result#<-----and this 
     return result 
+0

爲什麼你要複製這個函數呢?它應該工作得很好。只需導入它,然後使用它。 'from django.utils.functional import memoize; memoize的(富)'。 – jcdyer 2010-01-06 12:47:49

回答

2

memoize功能,我假設cachedict。另外,因爲a是list,所以b也是list,列表不可散列。使用tuple

嘗試

a = (1, 2, 3, 4) # Parens, not brackets 
b = a[:2] 
c = {} # Curly braces, not brackets 
c[b] = 'sss' 
2

什麼已經得到了你的問題與memoize的功能您發佈呢?推測(雖然我們必須猜測,因爲你沒有發佈實際的錯誤),你會得到一個TypeError。這是由於兩個錯誤。

首先,c是一個列表。所以你不能使用任意鍵,你只能使用整數索引。想必你的意思是這裏定義的字典:c = {}

其次,你要在聲明清單2 - b等於[1, 2] - 這不是一個有效的字典索引。 a應該是一個元組:a = (1, 2, 3, 4)

我必須重申其他人一直給你的建議。請先找到編程介紹,並在嘗試複製您不理解的高級Python代碼之前閱讀它。

相關問題