Python使用对象列表迭代对象

问题描述 投票:1回答:4

是否可以遍历包含对象列表的对象。

例如,我有以下课程

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
python list tree loops
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

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

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)

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

在这种情况下。

Example

page = Page('FirstPage', [
        Page('FirstChild', [
                Page('FirstChildChild'),
                Page('SecondChildChild'),
                ]),
        Page('SecondChild'),
        ])

for p in page.walk():
    print(p.name)

Output

FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild
© www.soinside.com 2019 - 2024. All rights reserved.