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

2024-09-29 17:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具体的问题,在这个问题中,我观察到python中所有的引用和取消引用的混淆。我有一个全局结构wordhistory,我在函数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的引用后面的值。这看起来不像这样。相反,我怀疑只有局部变量从对字典的引用更改。在

以下变体可以使用,但我想保存所有空假期字典的内存:

^{pr2}$

Tags: 函数innoneif字典current级别全局
1条回答
网友
1楼 · 发布于 2024-09-29 17:20:40

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

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]

相关问题 更多 >

    热门问题