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'永遠不會運行。您也可以使用'collections.Counter'來計算單詞列表中的單詞出現次數。 – M4rtini
1)行'#1'運行,我檢查了它。 2)比這更復雜一點。 – user1850980
@ user1850980你確定'#2'的縮進是正確的嗎? – Anton