2014-02-27 48 views
0

我有一個特定的問題,在這個問題中我觀察到python中引用和解引用的所有混淆。我有一個全球性的結構wordhistory我改變各個層次的功能addWordHistory內:Python:函數中全局變量的引用和解引用

wordhistory = dict() 

def addWordHistory(words): 
    global wordhistory 
    current = wordhistory 
    for word in words: 
     if current is None: 
      current = {word:[None,1]} #1 
     else: 
      if word in current: 
       current[word][1] += 1 
      else: 
       current[word] = [None,1] 
    current = current[word][0]   #2 

在行#1,我想改變已經在行#2被分配給本地變量current參考後面的值。這似乎並沒有像這樣工作。相反,我懷疑只有局部變量從引用更改爲字典。

下面的變型的作品,但我想保存所有的空休假字典的記憶:

wordhistory = dict() 

def addWordHistory(words): 
    global wordhistory 
    current = wordhistory 
    for word in words: 
     if word in current: 
      current[word][1] += 1 
     else: 
      current[word] = [dict(),1] 
     current = current[word][0] 
+1

行'#1'永遠不會運行。您也可以使用'collections.Counter'來計算單詞列表中的單詞出現次數。 – M4rtini

+0

1)行'#1'運行,我檢查了它。 2)比這更復雜一點。 – user1850980

+0

@ user1850980你確定'#2'的縮進是正確的嗎? – Anton

回答

1

爲了能夠改變當前列表中的項目,你需要存儲的參考列表,而不僅僅是您需要更改的項目:

def addWordHistory(words): 
    current = [wordhistory, 0] 
    for word in words: 
     if current[0] is None: 
      current[0] = dict() 
     children = current[0] 
     if word in children: 
      children[word][1] += 1 
     else: 
      children[word] = [None, 1] 
     current = children[word]