0

我有这样的UML图:

                   学校
                      |
                   老师
                      |
                   孩子们  

我正在访问类SchoolTeacher 和Childrenpython 中的数据,如下所示:

for Teacher in School.getTeachers():
        print Teacher.getName()
        for Children in Teacher.getChildrens():
            print Children.getName()

这是我得到的输出:

史密斯先生
一种
乙
C
D
乙
F
保罗先生
D
乙
F

我想比较下teacher1每个孩子的名字和老师二下的每个孩子的名字。

这两个的输出应该是:

A,B,C 不在 Paul 先生手下

4

1 回答 1

0

基本代码

使用集合,像这样:

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
于 2013-03-18T16:48:01.700 回答