微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将按字母顺序排列的节点添加到python中的双向链表

如何解决将按字母顺序排列的节点添加到python中的双向链表

我正在为大学做一个项目。我有一个双向链表来定义一个健康中心类。另外,我有患者班:

import os.path

class Patient:
    # Class to represent a Patient
    def __init__(self,name,year,covid,vaccine):
        self.name = name
        self.year = year
        self.covid = covid
        self.vaccine = vaccine
        
    def __str__(self):
        return self.name + '\t' + str(self.year) + '\t' + str(self.covid) + '\t' + str(self.vaccine)


class HealthCenter(DList):
    # Class to represent a Health Center
    def __init__(self,filetsv = None):
        super(HealthCenter,self).__init__()

        if filetsv is None or not os.path.isfile(filetsv):
            self.name = ''

        else: 
            print('Loading the data for the health center from the file',filetsv)
    
            self.name = filetsv.replace('.tsv','')
            tsv_file = open(filetsv)
            read_tsv = csv.reader(tsv_file,delimiter = "\t")
    
    
            for row in read_tsv:
                name = row[0]
                year = int(row[1])
                covid = False
                
                if int(row[2]) == 1:
                    covid = True

                vaccine = int(row[3])
                self.addLast(Patient(name,vaccine))

我的问题是我必须按字母顺序将患者作为节点添加到健康中心所在的列表中。 这是我的代码

    def addPatient(self,patient):
        new_node = DNode(None)
        new_node.elem = patient
        new_node.elem.name = patient.name
        new_node.elem.year = patient.year
        new_node.elem.covid = patient.covid
        new_node.elem.vaccine = patient.vaccine
        current = self._head
        current.elem = self._head.elem
        
        # if empty
        if self.isEmpty() == True:
            self._head = new_node
            self._tail = new_node
            self.size = 1
        else:
            i = 0
            while current.elem.name != patient.name and current.elem.name < patient.name:
                current = current.next
                i += 1
            if current.elem.name == patient.name:
                if current.elem == patient:
                    return print("This patient already exists")
                else:
                    self.insertAt(i,new_node)
                    return print("WARNING \n A patient with the same name already exists: \n",str(current.elem),"Added patient: \n",patient)
            elif current.elem.name > patient.name:
                return self.insertAt(i-1,new_node)

它给了我以下错误


  File "C:.../phase 1 spyder.py",line 73,in addPatient
    while (current.elem.name != patient.name) and (current.elem.name < patient.name):

AttributeError: 'nonetype' object has no attribute 'elem'

我不明白为什么,我在其他函数中定义了变量 current 并将其用作 current.elemcurrent.elem.name 或其他属性,如 covid、year 或vaccine ,我没有收到此错误

请帮忙

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。