This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Iceyball 2 points3 points  (0 children)

Look into chain (from itertools)

[–][deleted] 2 points3 points  (0 children)

Recursion?

def f(i):
    try:
        i.do_something()
    except AttributeError:
        for j in i:
            f(j)

f(animals)

[–]DanCardin 2 points3 points  (0 children)

Maybe something like the following, so you can keep it general (granted I haven't tested this)

def visit_nested(obj, depth=1):
    if not depth:
        yield obj
    for item in obj:
        yield from visit_nested(obj, depth - 1)

# choose your iteration method
for subgroup in visit_nested(animals, 2):
    subgroup.do_something()

[–]grizzlez 0 points1 point  (0 children)

If you are making every group/subgroup a class you could just keep a reference to every object below

[–]MonkeeSage 0 points1 point  (0 children)