将类实例追加到另一个类的列表变量时,如何摆脱重复?

时间:2018-02-17 15:31:40

标签: python class

所以我试图在The_Term类中添加一个单元,但unit_type(核心和基础)不能在unitlist中重复。将两个相同类型的单元添加到单元列表后,它仍将两个单元附加到列表中,而不是拒绝第二个单元。

class The_Unit():   

    def __init__(self,code,name, unit_type, prereq, maxStuNum, students):
        self.code = code
        self.name = name
        self.unit_type = unit_type
        self.prereq = list(prereq)
        self.maxStuNum = maxStuNum
        self.students = list(students)

class The_Term():


    def __init__(self,termcode, startdate, enddate, unitlist):
        self.termcode = termcode
        self.startdate = startdate
        self.enddate = enddate
        self.unitlist = list(unitlist)


    def __str__(self):
        return  'Term Code: ' + self.termcode + \
                '\nStart Date: ' + self.startdate + \
                '\nEnd Date: ' + self.enddate + \
                 '\nUnitlist: ' + ','.join((str(x) for x in self.unitlist))

    def addunit(self,unit):
        for x in self.unitlist:
           if x == 'foundation' or 'core':
                print("error")
        else:
            self.unitlist.append(unit.unit_type)
            self.unitlist.append(unit.code)

unit1 = The_Unit('FIT9133','programming foundations in python','foundation',
['none'],'3', ['saki','michelle'])
unit2 = The_Unit('FIT5145','Inroduction to Data Science','core',
['FIT9133','MAT9004','FIT9132'],'6', ['saki','michelle','Ruchi'])
unit3 = The_Unit('FIT9132','Introduction to Data Base','foundation',
['none'],'3', ['saki','michelle'])


term2 = The_Term('TP2','03/03','19/04', '' ) 

term2.addunit(unit1)
term2.addunit(unit3)
term2.addunit(unit2)

print(term2)



error
error
error
error
error
error
Term Code: TP2
Start Date: 03/03
End Date: 19/04
Unitlist: foundation,FIT9133,foundation,FIT9132,core,FIT5145    

1 个答案:

答案 0 :(得分:0)

根据您要添加的内容,检查基础或核心是否已在列表中。如果是,则打印错误,否则追加。

def addunit(self,unit):
    if 'foundation' in self.unitlist and unit.unit_type  == 'foundation' \
        or 'core' in self.unitlist and unit.unit_type  == 'core':
           print("error")             
    else:
        self.unitlist.append(unit.unit_type)
        self.unitlist.append(unit.code)

您不应该将完整的单位添加到该术语的单位列表中吗?

输出:

error
Term Code: TP2
Start Date: 03/03
End Date: 19/04
Unitlist: foundation,FIT9133,core,FIT5145