简体   繁体   English

在 for 循环中将动态字典附加到 Python 中的列表

[英]Append dynamic dictionary to a list in Python in a for loop

This is initial program for implementing Prefix Tree for a Question.这是为问题实现前缀树的初始程序。 Later i used the dict.copy() function to deal with dynamic behavior of dictionary, but couldn't get the desired output .后来我使用 dict.copy() 函数来处理字典的动态行为,但无法获得所需的输出。

end='end'
def make_trie(word,root):
    current_dict=root
    for letter in word:
        current_dict=current_dict.setdefault(letter,{})
    current_dict[end]=end
    return root

s=[]
n=int(input())
t=[]
for _ in range(n):
    s.append(input())

    if  _==0:
        d=make_trie(s[-1],{})

    else:
        d=make_trie(s[-1],d)
    t.append(d.copy())
print(t)

List i am getting for input : 4 abcd abce abcdex abcde我要输入的列表: 4 abcd abce abcdex abcde
is :是 :
[{'a': {'b': {'c': {'d': {'end': 'end', 'e': {'x': {'end': 'end'}, 'end': 'end'}}, 'e': {'end': 'end'}}}}}, {'a': {'b': {'c': {'d': {'end': 'end', 'e': {'x': {'end': 'end'}, 'end': 'end'}}, 'e': {'end': 'end'}}}}}, {'a': {'b': {'c': {'d': {'end': 'end', 'e': {'x': {'end': 'end'}, 'end': 'end'}}, 'e': {'end': 'end'}}}}}, {'a': {'b': {'c': {'d': {'end': 'end', 'e': {'x': {'end': 'end'}, 'end': 'end'}}, 'e': {'end': 'end'}}}}}]
Which is 4 times the final Dictionary.这是最终词典的 4 倍。
Please suggest some way to deal with this issue.请建议一些方法来处理这个问题。

Since the trie is a dictionary of dictionaries, you need to deep copy instead of shallow.由于trie是字典的字典,你需要深拷贝而不是浅拷贝。 Try this:尝试这个:

from copy import deepcopy  

end='end'
def make_trie(word,root):
    current_dict=root
    for letter in word:
        current_dict=current_dict.setdefault(letter,{})
    current_dict[end]=end
    return root

s=[]
n=int(input())
t=[]
for _ in range(n):
    s.append(input())

    if  _==0:
        d=make_trie(s[-1],{})

    else:
        d=make_trie(s[-1],d)
    t.append(deepcopy(d))
print(t)  

When you shallow copy, you just copy the outermost dictionary, so the inner dictionaries are still shared between copied dictionaries.当你浅拷贝时,你只是复制最外层的字典,所以内部字典仍然在复制的字典之间共享。

Another option would be to cast the dictionary object to a string and back, using the Python 3's eval function or the inbuilt ast library's function literal_eval, if your dictionary is not too big.如果您的字典不是太大,另一种选择是使用 Python 3 的 eval 函数或内置 ast 库的函数literal_eval 将字典对象转换为字符串并返回。 You can try the following:您可以尝试以下操作:

end='end'
def make_trie(word,root):
    current_dict=root
    for letter in word:
        current_dict=current_dict.setdefault(letter,{})
    current_dict[end]=end
    return root

s=[]
n=int(input())
t=[]
for _ in range(n):
    s.append(input())

    if  _==0:
        d=make_trie(s[-1],{})

    else:
        d=make_trie(s[-1],d)

    d_str = str(d)   
    t.append(eval(d_str))
print(t)

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

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