为什么 .clear() 只有 return 最后一次迭代

Why does .clear() only return last iteration

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

It is a Node of the Graph if the word's last letter is equal of the second name first letter

我的列表:

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']}

我做错了什么?

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

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