我需要编写一个包含两个函数的Python脚本。一个函数是返回(p)和Take(p)的后代子项并返回(p)的祖先。
我制作了一个返回(p)子节点的脚本。
parent = [("Homer","Bart"),("Homer","Lisa"),("Abe","Homer"),("Bart","Jim"),("Jim","Kim"),("Lisa","Lora")]
def child(p): #definition of child function()
result = []
for x in parent:
if x[0] == p:
print(x[1])
result.append(x[1])
return result
def grandChild (p):
result = []
children = child(p)
for x in children:
for y in parent:
if x == y[0]:
result.append(y(1))
return result
p = "Homer"
children = child(p) # my caller question
print(p, " has child ", children)
我无法弄清楚该怎么做。
答案 0 :(得分:0)
您的退货声明在错误的地方。它们应该在循环之外:
def f():
for loop
stuff
return ...
如果您想要更简洁的版本:
#find children of parent p
[child for parent, child in list_of_parents if parent == p]
#find parent of child c
[parent for parent, child in list_of_parents if child == c]