문제

In web2py I have been trying to break down this list comprehension so I can do what I like with the categories it creates. Any ideas as to what this breaks down to?

def menu_rec(items): 
    return [(x.title,None,URL('shop', 'category',args=pretty_url(x.id, x.slug)),menu_rec(x.children)) for x in items or []]

In addition the following is what uses it:

response.menu = [(SPAN('Catalog', _class='highlighted'), False, '',
             menu_rec(db(db.category).select().as_trees()) )]

So far I've come up with:

def menu_rec(items):
    for x in items:
        return x.title,None,URL('shop', 'category',args=pretty_url(x.id, x.slug)),menu_rec(x.children))

I've got other variations of this but, every variation only gives me back 1(one) category, when compared to the original that gives me all the categories.

Can anyone see where I'm messing this up at? Any and all help is appreciated, thank you.

도움이 되었습니까?

해결책

A list comprehension builds a list by appending:

def menu_rec(items): 
    result = []
    for x in items or []:
        url = URL('shop', 'category', args=pretty_url(x.id, x.slug))
        menu = menu_rec(x.children)  # recursive call
        result.append((x.title, None, url, menu))
    return result

I've added two local variables to break up the long line somewhat, and to show how it recursively calls itself.

Your version returned directly out of the for loop, during the first iteration, and never built up a list.

다른 팁

You don't want to do return. Instead append to a list and then return the list:

def menu_rec(items):
    result = []
    for x in items:
        result.append(x.title,None,URL('shop', 'category',args=pretty_url(x.id, x.slug)),menu_rec(x.children)))
    return result

If you do return, it will return the value after only the first iteration. Instead, keep adding it to a list and then return that list at the end. This will ensure that your result list only gets returned when all the values have been added instead of just return one value.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top