这是我的代码:class member: def __init__(self, name): self.name = name def get_name(self, name): self.name = name def __str__(self): return self.nameclass create_graph: def __init__(self): self.some_dict = dict() def add(self, name): if name is None: raise TypeError print(name not in self.some_dict) if name not in self.some_dict: self.some_dict[name] = [] else: print(str(name) + "is already present") def link(self, p1, p2): if p1 in self.some_dict: self.some_dict[p1].append(p2) else: self.some_dict[p1] = [p2]some_graph = create_graph()list_person = ['abc', 'xyz', 'mno', 'pqr']for person in list_person: some_graph.add(member(person))print(len(some_graph.some_dict))for i in range(len(list_person)-1): some_graph.link(i,i+1)print(len(some_graph.some_dict))我无法在此代码中找到错误。当 add 函数被调用时,我得到 True 消息,表明它被添加了。第一个打印语句打印出键的数量是 4,但在添加链接后,它说键是 7。即使添加了链接,我也希望只有 4。谢谢您的帮助 !
3 回答
弑天下
TA贡献1818条经验 获得超8个赞
打印出有问题的字典。
print(some_graph.some_dict)
产生
{<__main__.member object at 0x7fe8326abe80>: [], <__main__.member object at 0x7fe8326abeb8>: [], <__main__.member object at 0x7fe8326abe48>: [], <__main__.member object at 0x7fe8326abef0>: []}
该字典的键是类的实例member,而不是列表中的字符串list_person。
我你做了:
persons_in_graph_dict = {k.name for k in some_graph.some_dict}
for person in list_person:
print(person)
print(person in persons_in_graph_dict)
print()
你会得到:
abc
True
xyz
True
mno
True
pqr
True
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
您将实例存储为密钥。调用name()
以获取名称尝试测试如下
for i in some_graph.some_dict: print ((i.name) in list_person)
添加回答
举报
0/150
提交
取消