是否可以迭代包含对象列表的对象。
例如,我有以下课程
Class Page(object)
def __init__(self, name):
self.name = name
self.pages = []
然后我创建一个新的Page对象并向其添加其他页面对象。
page = Page('FirstPage')
apagepage = Page('FirstChild')
anotherpagepage = Page('SecondChild')
apagepage.pages.append(Page('FirstChildChild'))
apagepage.pages.append(Page('SecondChildChild'))
page.pages.append(apagepage)
page.pages.append(anotherpagepage)
我想做的是
for thispage in page:
print thispage.name
获得以下输出
FirstPage
FirstChild
SecondChild
FirstChildChild
SecondChildChild
所以我获得了所有的第1级,然后是第2级,然后是第3级。
但是,也可以找到以下输出
FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild
答案 0 :(得分:3)
您可以定义__str__
from itertools import chain
class Page(object):
def __init__(self, name):
self.name = name
self.pages = []
def __str__(self):
return "\n".join(chain([self.name], map(str, self.pages)))
然后你可以print page
或者,如果您希望使用for循环
,则可以定义迭代器class Page(object):
def __init__(self, name):
self.name = name
self.pages = []
def __iter__(self):
yield self
for page in self.pages:
for i in page:
yield i
答案 1 :(得分:1)
递归地执行:
class Page(object):
def __init__(self, name):
self.name = name
self.pages = []
def __iter__(self):
for p in self.get_children_pages(self):
yield p
def get_children_pages(self, start_page):
result = [start_page.name]
for this_page in start_page.pages:
result.extend(self.get_children_pages(this_page))
return result
>>>>for p in page:
.... print p
FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild
答案 2 :(得分:0)
以递归方式执行
def print_all_pages(page):
print page.name
if len(page.pages) == 0 then:
return
else:
for child_page in page.pages:
print_all_pages(child_page)
def print_pages(pages_collection):
for page in pages_collection:
print_all_pages(page)
答案 3 :(得分:0)
class Page(object):
def __init__(self, name, pages=None):
self.name = name
self.pages = pages if pages is not None else []
def __iter__(self):
return iter(self.pages) # only immediate children
def walk(self, topdown=True): # all pages recursively
if topdown:
yield self
for page in self:
yield from page.walk(topdown)
if not topdown:
yield self
您可以将Python< 3.3上的yield from
替换为:
for subpage in page.walk(topdown):
yield subpage
在这种情况下。
page = Page('FirstPage', [
Page('FirstChild', [
Page('FirstChildChild'),
Page('SecondChildChild'),
]),
Page('SecondChild'),
])
for p in page.walk():
print(p.name)
FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild