[英]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. 所以我试图将一个单元添加到The_Term类中,但是unit_type(核心和基础)不能在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.