如果使用Python 2。7,你需要保持自己的iterables的堆栈,做循环:
from operator import methodcaller
def recursive(obj, iterater, yielder, depth):
iterate = methodcaller(iterater)
xs = [iterate(obj)]
while xs:
try:
x = xs[-1].next()
if len(xs) != depth:
xs.append(iterate(x))
else:
yield getattr(x, yielder)
except StopIteration:
xs.pop()
这从迭代函数更一般的递归ichain的专业情况:
def recursive_ichain(iterable_tree):
xs = [iter(iterable_tree)]
while [xs]:
try:
x = xs[-1].next()
if isinstance(x, collections.Iterable):
xs.append(iter(x))
else:
yield x
except StopIteration:
xs.pop()
及一些测试对象:
class Thing(object):
def __init__(self, thing):
self.thing = thing
class Parent(object):
def __init__(self, *kids):
self.kids = kids
def children(self):
return iter(self.kids)
test_obj = Parent(
Parent(
Parent(Thing('one'), Thing('two'), Thing('three')),
Parent(Thing('four')),
Parent(Thing('five'), Thing('six')),
),
Parent(
Parent(Thing('seven'), Thing('eight')),
Parent(),
Parent(Thing('nine'), Thing('ten')),
)
)
并对其进行测试:
>>>for t in recursive(test_obj, 'children', 'thing', 3):
>>> print t
one
two
three
four
five
six
seven
eight
nine
ten
Personnaly我倾向于将yield getattr(x, yielder)
更改为yield x
以访问叶对象本身并显式访问该对象。即
for leaf in recursive(test_obj, 'children', 3):
print leaf.thing
尽管如此,通用的解决方案,但这可能在这种情况下工作,但没有一个内置的方式已经做到这一点? – Paradoxis
我的意思更多,因为动态调用'children'和'x.thing' – Paradoxis
@Paradoxis你确实可以。假设'children'返回一个迭代。让我修改我的答案。 –