1

是否可以迭代包含对象列表的对象。

例如,我有以下课程

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

所以我得到了所有的第一级,然后是第二级,然后是第三级。

但是,也会找到以下输出

FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild
4

4 回答 4

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
于 2012-10-23T04:35:58.580 回答
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
于 2012-10-23T04:28:28.080 回答
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)
于 2012-10-23T04:48:43.400 回答
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

您可以yield from在 Python <3.3 上替换为:

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
于 2012-10-23T10:36:49.910 回答