I have a specific problem in which I observe all the confusion of reference and dereference in python. I have a global structure wordhistory
which I change on various levels inside a function addWordHistory
:
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
In line #1
, I want to change the value behind the reference that has been assigned to the local variable current
in line #2
. This does not seem to work like this. Instead, I suspect that only the local variable is changed from a reference to a dictionary.
The below variant works, but I want to save the memory of all the empty leave dictionaries:
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]
To be able to change an item of the current list, you need to store the reference to the list, not just to the item you need to change:
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.