- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在实现一个带有参数名称、职位和 child 的“人”类。函数“desc”应返回家谱下的人员列表。
到目前为止,我已经这样做了:
class Person():
def __init__(self, name, title, children=None):
self.name = name
self.title = title
if children is None:
self.children = []
else:
self.children = children
def desc(self):
self.out = []
if self.children:
for kid in self.children:
self.out.append(kid)
return self.out
p1 = Person("p1", "test")
p2 = Person("p2", "test", children = [p1])
p3 = Person("p3", "test")
p4 = Person("p4", "test", children = [p2, p3])
p5 = Person("p5", "boss", children = [p4])
print [person.title for person in p5.desc()]
# desired output:
# ['test', 'test', 'test','test']
print [person.name for person in p5.desc()]
# desired output:
# ['p4', 'p2', 'p1', 'p3']
但我的实际输出看起来并不像期望的那样。所以,我的问题是:你将如何拯救 children ?在一个简单的列表中?问题显然出在 def desc() 中。感谢您的帮助!
最佳答案
你必须递归 children
列表:
def desc(self):
out = []
for kid in self.children:
out.append(kid)
out.extend(kid.desc())
return out
这使用了 desc()
当前对象上的方法,然后在每个列出的子对象上调用相同的方法以扩展当前结果列表。这一直持续到遇到没有 child 的对象。
请注意 out
不需要是实例的属性;我保留了一个局部变量。
这会产生您预期的输出:
>>> class Person():
... def __init__(self, name, title, children=None):
... self.name = name
... self.title = title
... if children is None:
... self.children = []
... else:
... self.children = children
... def desc(self):
... out = []
... for kid in self.children:
... out.append(kid)
... out.extend(kid.desc())
... return out
...
>>> p1 = Person("p1", "test")
>>> p2 = Person("p2", "test", children = [p1])
>>> p3 = Person("p3", "test")
>>> p4 = Person("p4", "test", children = [p2, p3])
>>> p5 = Person("p5", "boss", children = [p4])
>>> print [person.title for person in p5.desc()]
['test', 'test', 'test', 'test']
>>> print [person.name for person in p5.desc()]
['p4', 'p2', 'p1', 'p3']
所以 p5.desc()
添加 p4
到 out
列表,然后用 p4.desc()
的结果扩展列表. p4.desc()
添加 p2
到它的本地out
列表,用 p2.desc()
的结果扩展它, 然后添加 p3
至 out
并用 p3.desc()
扩展它等
关于Python:家族级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26869467/
我需要在 php 和 MySQL 中构建家谱。我对那里缺乏开源可定制的 html 家谱构建软件感到非常惊讶,但我离题了。我花了很多时间阅读有关存储 MySQL 有向图和家谱的内容。一切对我来说都有意义
我尝试将数据添加到数据库。但是有这个错误。 Illuminate \ Database \ Eloquent \ MassAssignmentException fam 'fam' 是名称优先参数。
在 lisp 家族(编辑:lisp-1)语言中是否有一种方法可以根据其作为函数或参数的位置来区分符号求值(即在求值时重写该符号的求值) ? 作为一个例子(我不需要这个功能,这是一个例子),我想在一组对
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 7 年前。 Improve this qu
我是一名优秀的程序员,十分优秀!