Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
reduce nested for-loops
#11
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]
Reply
#12
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [redistribution] Reduce number + size of dependencies? Winfried 2 653 Jan-31-2025, 10:17 PM
Last Post: snippsat
  Adding values with reduce() function from the list of tuples kinimod 10 5,441 Jan-24-2023, 08:22 AM
Last Post: perfringo
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 2,937 Aug-19-2022, 11:07 AM
Last Post: dm222
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 2,925 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  breaking out of nested loops Skaperen 3 1,985 Jul-18-2022, 12:59 AM
Last Post: Skaperen
  Break out of nested loops muzikman 11 5,090 Sep-18-2021, 12:59 PM
Last Post: muzikman
  How to break out of nested loops pace 11 7,613 Mar-03-2021, 06:25 PM
Last Post: pace
  Nested for Loops sammay 1 12,748 Jan-09-2021, 06:48 PM
Last Post: deanhystad
  How do I reduce the time to Invoke Macro via Python? JaneTan 1 2,734 Dec-28-2020, 06:46 AM
Last Post: buran
  How to reduce the following code to run in sequence? Giggel 4 3,531 Jun-28-2020, 01:31 AM
Last Post: Giggel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020