简体   繁体   中英

How to get rid of duplicates when you append a class instance to another class's list variable?

So I am trying to add a unit to the The_Term Class but the unit_type (core and foundation) cannot be repeated in the unitlist. After adding two units of the same type on to the unitlist it is still appending both units into the list instead of rejecting the second addition.

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    

Check if foundation or core are already in list depending on what you want to add. If so, print error, else append.

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)

Shouldn't you add the complete unit to the unitlist of that term?

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM