我试图创建一个节点图作为字典,但得到了一些意想不到的结果:
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
只清空列表,但相同的列表被分配给键,然后再次清除;列表的最终状态是所有键的状态。考虑为每个项目创建一个新列表:相关问题 更多 >
编程相关推荐