为什么.clear()只返回最后一次迭代

时间:2017-05-19 09:49:36

标签: python python-3.x dictionary graph-theory

我正在尝试创建一个节点图表作为字典,但我得到了一些意想不到的结果:

  

如果单词的最后一个字母等于,则为图表的节点   第二个名字第一个字母

我的列表

names = ["Mark", "Kelly", "Kurt", "Terk"]

我的代码

n = [ x.lower() for x in names ]
graph = {}
temp = []
for x in n:
    temp.clear()
    for y in n:
        if(x[-1]==y[0] and not x==y):
            temp.append(y)
    graph[x] = temp

结果

{'kurt': ['kelly', 'kurt'], 'terk': ['kelly', 'kurt'], 'kelly': ['kelly', 'kurt'], 'mark': ['kelly', 'kurt']}

预期行为

{'kurt': ['terk'], 'terk': ['kelly', 'kurt'], 'kelly': [], 'mark': ['kelly', 'kurt']}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

.clear仅清空列表,但是将相同的列表分配给密钥,然后再次清除;列表的最终状态是所有键的所有内容。考虑为每个项目创建一个新列表:

...
for x in n:
    temp = []
    for y in n:
        if x[-1]==y[0] and x!=y:
            temp.append(y)
    graph[x] = temp
相关问题