Python - 链表问题和相关

2024-04-23 08:48:48 发布

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

我正在开发一个客户端/服务器来进行简单的聊天。客户端在VB和 python中的服务器。你知道吗

我想让我的服务器存储我的消息,我认为最聪明的方法是建立一个链表(我是python的新手,但在C#中要高级得多)。你知道吗

我尝试存储的内容包括:

  • 收件人(此处称为dest)
  • 消息(称为msg)

我不知道有多少条,如果我有一条新的消息给已经存储了消息的人,我会覆盖它

我在课堂上试过了

class tabmessage:
    def __init__(self, dest=None,msg=None, next=None): 
        self.dest = dest
        self.msg = msg
        self.next = None

这就是所谓的

#I create the top of the chain on the beginning
messages = tabmessage(dest='Control',msg='Message Integrity')

。。。之后在函数中

#Setting the top of the chain
(d,m,s) = (messages.dest,messages.msg,messages.next)
#Looking for a similar dest in chain and getting at the end at the same time
while True:
        if (d == tempdest):
            m = (tempmsg+".")[:-1]
            print("Overwrite of msg for" + d + " : " + m);
            return
        if (s is None):
            break
        (d,m,s)=(s.dest,s.msg,s.next)
#If I did not found it i try to add it to the chain
s = tabmessage(dest=(tempdest+".")[:-1],msg=(tempmsg+".")[:-1])
print("Trying to add : " + s.dest + " : " + s. msg)

最后一张照片看起来不错:

Trying to add : User : This is my message

但如果我这么做了:

print("Trying to add : " + messages.next.dest + " : " + messages.next. msg)

发生错误(NoneType没有dest元素…),因此top仍然是单独的。你知道吗

或者如果有更聪明的方法在python中实现它呢?你知道吗


Tags: ofthetoself服务器noneadd消息
2条回答

我试着在更高的节点上进行操作,结果成功了。 现在我有:

#Setting the top of the chain
cunode = messages
#Looking for a similar dest in chain and getting at the end at the same time
while True:
    if (cunode.dest == tempdest):
        cunode.msg = (tempmsg+".")[:-1]
        print("Overwrite of msg for" + cunode.dest + " : " + cunode.msg);
        return
    if (cunode.next is None):
        break
    cunode = cunode.next

#If I did not found it i try to add it to the chain
cunode.next = tabmessage(dest=(tempdest+".")[:-1],msg=(tempmsg+".")[:-1])

对我来说也一样。。。你知道吗

如果我正确理解了你的函数,你就找到了你想要的节点

if (d == tempdest):

然后你写下你的信息并返回。因为您返回,所以底部为新节点分配s的语句永远不会运行。我想你应该在那里休息一下。我不确定这是您唯一的问题,但我认为这就是您的列表没有获得额外节点的原因。你知道吗

相关问题 更多 >