我有一个为python中的person类设计的类模型。一个人是一个学生,可以有0.1或多个顾问。一个人也可以有其他属性,如姓名,学校,毕业年份,他所从事的分类,获得的学位等。
我已经为类中的每个属性设置并获取了方法。 防爆。 set_advisor(self,advisor)将顾问插入学生顾问的列表中。 set_year(self,year)设定学生的毕业年份。
类似地,get_advisor(self)返回学生的顾问。等等..
最后我填充对象并将其命名为人。
如果我想获得一年毕业的学生名单,我只需写一下
print [people[p].name for p in people if people[p].year="YEAR"]
现在,我想写一个查询,比如说...列出一年毕业的学生,他们的顾问追溯说一些“abc”...... 例如,数据集看起来像这样..
person a graduated in year 1990
person b graduated in year 1990
person c graduated in year 1991
person d graduated in year 1990
person a was advised by person e
person e was advised by person f
person f was advised by person g
person g was advised by person abc
person b was advised by person i
person i was advised by person abc
person c was advised by person abc
person d was advised by person h
person h was advised by person k
现在,我想编写一个递归查询来跟踪那些在1990年毕业并且顾问追溯到abc的人。在上述情况下,它应该只给我a和b作为结果。
我该如何解决这个问题。我在语法和制定查询时遇到问题。与上面的表格查询相同。 任何人都可以为此提供帮助。
同样..我怎么写查询..say .. 得到那些从事某种分类并在同一年毕业并且他们的顾问也在同一分类上工作的学生。
感谢。
答案 0 :(得分:1)
您可以在课堂上编写一个方法,例如:
has_advisor(self, advisor):
if not self.advisor:
return False
elif advisor in self.advisor:
return True
else
return self.advisor.has_advisor(advisor)
这可以让你查询:
e = people['e']
e_in_advisor_tree_and_grad_in_1990 = [p for p in people if p.has_advisor(e) and p.year == 1990]
使用大型数据集会很快变得非常昂贵,所有数据集都会同时保存在内存中。