我正在尝试实现在树结构中获取 child 的 child 的可能性。
这是我想要的例子。
到目前为止我做了什么。
class Children(list):
def __init__(self, l):
list.__init__(l)
self.l = l
@property
def children(self):
_children = []
for child in self.l:
_children.extend(child.children)
return Children(_children)
class Person:
def __init__(self):
self._children = Children([])
def add_child(self, child):
self._children += [child]
@property
def children(self):
return self._children
me = Person()
sister = Person()
brother = Person()
father = Person()
cousin = Person()
uncle = Person()
grandpa = Person()
ancient_grandpa = Person()
father.add_child(me)
father.add_child(sister)
father.add_child(brother)
uncle.add_child(cousin)
grandpa.add_child(father)
grandpa.add_child(uncle)
ancient_grandpa.add_child(grandpa)
print ancient_grandpa # ancient_grandpa
print ancient_grandpa.children # [grandpa]
print ancient_grandpa.children.children # [father, uncle] but got []
print ancient_grandpa.children.children.children # [me, sister, brother, cousin] but got []
请注意,这只是一个最小的工作示例。事实上,我的树比这更深。
最佳答案
在处理树时,最常见的方法是使用递归从树中提取数据和修改。
你也许可以这样做:
class Person(object):
def __init__(self, name):
self.name = name
self.children = []
def get_generation_n(self, n):
if n <= 0:
return []
if n == 1:
return self.children
generation = []
for child in self.children:
generation += child.get_generation_n(n - 1)
return generation
def add_child(self, person):
self.children.append(person)
def __repr__(self):
return self.name
grandpa = Person('Grand-Pa')
p1 = Person('p1')
p2 = Person('p2')
p3 = Person('p3')
p4 = Person('p4')
p5 = Person('p5')
p3.add_child(p5)
p3.add_child(p4)
p1.add_child(p2)
grandpa.add_child(p1)
grandpa.add_child(p3)
print(grandpa.get_generation_n(1)) # prints [p1, p3]
print(grandpa.get_generation_n(2)) # prints [p2, p4, p5]
事实上,你只需要一个类。对于 child 来说,只是另一个人。
关于python - 在树中实现 children.children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47574277/