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

2024-05-15 08:58:20 发布

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

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

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

我做错什么了


Tags: oftheinforif节点namesis
1条回答
网友
1楼 · 发布于 2024-05-15 08:58:20

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

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

相关问题 更多 >