词典目录问题

2024-04-25 04:31:44 发布

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

我有以下代码:

n=4
arr=['abcd', 'abce', 'abcdex', 'abcde']
mainarr=[{}]
dic={}
for i in range(1,n+1):
    insert(dic,arr[i-1]+' ') #insert is a function that modifies dic
    print(dic)               #to see whats the current dic
    mainarr.append(dic.copy())

所以我得到了主

现在的问题是,不知何故,mainarr的第一个和第二个元素与预期的相同,但其余三个条目都相同,并且等于mainarr的最后一个元素的值…..请帮助我找出错误!!!你知道吗

输出为

{'a': 'abcd '}
{'a': {'b': {'c': {'d': 'abcd ', 'e': 'abce '}}}}
{'a': {'b': {'c': {'d': {' ': 'abcd ', 'e': 'abcdex '}, 'e': 'abce '}}}}
{'a': {'b': {'c': {'d': {' ': 'abcd ', 'e': {'x': 'abcdex ', ' ': 'abcde 
'}}, 'e': 'abce '}}}}

所以每次迭代后dic值都是正确的

但主要是

[{}, {'a': 'abcd '}, {'a': {'b': {'c': {'d': {' ': 'abcd ', 'e': {'x': 
'abcdex ', ' ': 'abcde '}}, 'e': 'abce '}}}}, {'a': {'b': {'c': {'d': {' ': 
'abcd ', 'e': {'x': 'abcdex ', ' ': 'abcde '}}, 'e': 'abce '}}}}, {'a': 
{'b': {'c': {'d': {' ': 'abcd ', 'e': {'x': 'abcdex ', ' ': 'abcde '}}, 'e': 
'abce '}}}}] #as you can see, first two elements are correct, but last 3 are 
             equal to final value of dic

如果有帮助的话,插入代码是

def insert(dic,string,depth=0):
    if type(dic)==dict:

        if string[depth] in dic.keys():
            dic[string[depth]]=insert(dic[string[depth]],string,depth+1)
            return dic
        else:
            dic[string[depth]]=string
            return dic
    else:


        if dic[depth]==string[depth]:
             return {dic[depth]:insert(dic,string,depth+1)}

        else:
            return {dic[depth]:dic,string[depth]:string}

Tags: 代码instringreturnifelseinsertarr
1条回答
网友
1楼 · 发布于 2024-04-25 04:31:44

dic.copy()只复制字典,不复制它的内容。您可以使用来自copy模块的copy.deepcopy。但是还有另一种方法可以将拷贝移到insert函数中,这样它总是返回一个拷贝。你知道吗

insert函数会改变字典:

    if string[depth] in dic.keys():
        dic[string[depth]]=insert(dic[string[depth]],string,depth+1)
        return dic
    else:
        dic[string[depth]]=string
        return dic

如果在insert函数中复制一次,问题就会消失:

    dic = dic.copy()
    if string[depth] in dic.keys():
        dic[string[depth]]=insert(dic[string[depth]],string,depth+1)
        return dic
    else:
        dic[string[depth]]=string
        return dic

结果是insert函数总是返回一个副本,然后主循环应该如下所示:

for i in range(1,n+1):
    dic = insert(dic, arr[i-1]+' ') # returns a copy that is mutated
    print(dic)               #to see whats the current dic
    mainarr.append(dic)

相关问题 更多 >