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

时间:2018-06-06 12:07:46

标签: python python-3.x dictionary

这是实现问题的前缀树的初始程序。后来我使用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)

列表我正在获取输入: 4 abcd abce abcdex abcde
是:
  [{'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'}}}}}]
这是最终词典的4倍 请提出一些解决此问题的方法。

2 个答案:

答案 0 :(得分:0)

由于trie是字典词典,因此需要深层复制而不是浅层。试试这个:

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)  

当您进行浅层复制时,您只需复制最外层的字典,因此内部字典仍然可以在复制的字典之间共享。

答案 1 :(得分:0)

另一种选择是,如果字典不是太大,则使用Python 3的eval函数或内置的ast库的函数literal_eval将字典对象转换为字符串并返回。您可以尝试以下操作:

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)
相关问题