繁体   English   中英

Python:函数中全局变量的引用和取消引用

[英]Python: reference and dereference of global variables in functions

我有一个特定的问题,其中我观察了python中引用和取消引用的所有混淆。 我有一个全局结构的wordhistory ,可以在函数addWordHistory各个级别上进行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

#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]

为了能够更改当前列表的项目,您需要存储对列表的引用,而不仅仅是对需要更改的项目的引用:

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM