猿问

字典键不存在,尽管它们被添加

这是我的代码:


class member:


    def __init__(self, name):

        self.name = name


    def get_name(self, name):

        self.name = name


    def __str__(self):

        return self.name


class 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。


谢谢您的帮助 !


30秒到达战场
浏览 188回答 3
3回答

弑天下

打印出有问题的字典。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:&nbsp; &nbsp; print(person)&nbsp; &nbsp; print(person in persons_in_graph_dict)&nbsp; &nbsp; print()你会得到:abcTruexyzTruemnoTruepqrTrue

斯蒂芬大帝

您将实例存储为密钥。调用name()以获取名称尝试测试如下for&nbsp;i&nbsp;in&nbsp;some_graph.some_dict: &nbsp;&nbsp;&nbsp;&nbsp;print&nbsp;((i.name)&nbsp;in&nbsp;list_person)
随时随地看视频慕课网APP

相关分类

Python
我要回答