基本代码
使用集合,像这样:
teachers = list(School.getTeachers())
teacher1 = teachers[0]
teacher2 = teachers[1]
diff = set(teacher1.getChildrens()) - set(teacher2.getChildrens())
print "%s are not under %s" % (", ".join(c.getName() for c in diff), teacher2.getName())
扩展示例
>>> class Student(object):
... def __init__(self, name):
... self.name = name
... def getName(self):
... return self.name
...
>>> class Teacher(object):
... def __init__(self, name, students):
... self.name = name
... self.students = students
... def getChildrens(self):
... return self.students
... def getName(self):
... return self.name
...
>>> class School(object):
... def __init__(self, teachers):
... self.teachers = teachers
... def getTeachers(self):
... return self.teachers
...
>>> students = [Student("A"), Student("B"), Student("C"), Student("D"), Student("E"), Student("F"), ]
>>> s = Teacher("Smith", students)
>>> p = Teacher("Paul", students[3:])
>>> school = School([s, p])
>>>
>>> teachers = list(school.getTeachers())
>>> teacher1 = teachers[0]
>>> teacher2 = teachers[1]
>>>
>>> diff = set(teacher1.getChildrens()) - set(teacher2.getChildrens())
>>> print "%s are not under %s" % (", ".join(c.getName() for c in diff), teacher2.getName())
B, C, A are not under Paul