Python Forum

Full Version: reduce nested for-loops
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
The comprehension (for the OP) would be like this:
class C:
    def __init__(self, size):
        self.list_of_ds = list(range(size))


class B:
    def __init__(self, size):
        self.list_of_cs = [C(size + 1) for _ in range(size)]


class A:
    def __init__(self, size):
        self.list_of_bs = [B(size + 1) for _ in range(size)]


a = A(2)
print([d for b in a.list_of_bs for c in b.list_of_cs for d in c.list_of_ds])
Output:
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
Agree with bowlofred above. What is the data you're working with? What does it represent? If it does have some hierarchical structure, then representing it that way (i.e. in some kind of tree) would make more sense.
Pages: 1 2