Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

66%
+2 −0
Q&A How to group a flat list of attributes into a nested lists?

The obvious way would be to simply start with an empty list of lists, loop through the input, and for each item decide which sublist to put it in. It's not super dev-friendly to remember which lis...

posted 2mo ago by matthewsnyder‭

Answer
#1: Initial revision by user avatar matthewsnyder‭ · 2024-03-18T21:51:36Z (about 2 months ago)
The obvious way would be to simply start with an empty list of lists, loop through the input, and for each item decide which sublist to put it in.

It's not super dev-friendly to remember which list was which. So instead, I think it's better to construct each sublist separately, and then combine them, so that you never have the problem of digging up a list.

The easy way to do this is to do multiple passes, so you can append each sublist to the main list once it's done:

```
nested = []
attrs = ['attr1', 'attr2', 'attr3']
for a in attrs:
    sublist = []
    for i in flat:
        if i.startswith('attr1'):
            sublist.append(i)
    if sublist:
        nested.append(sublist)

print(nested)
```

This may strike you as wildly inefficient, but it's not so bad. If the item is N things and there are K attributes, it's only `O(K*N)` which is not terrible. Furthermore, the runtime of each individual iteration is dominated by `sublist.append` which is more costly than `str.startswith`. It only does `append` `O(N)` times, and only `startswith` is evaluated `O(K*N)` times, which is pretty tolerable.

-----------------------------------------

You might not want to provide a hard coded list of attributes. These are easy to construct:
```
attrs = set()
for i in flat:
    a = i.split()[0]
    attrs.add(a)
```

This is a set, not a list like in my code (to avoid dealing with duplicates), but you can run a `for` loop on it just the same.

-------------------------

The more natural way to do this would be a dictionary:
```
nested = {}
for i in flat:
    # Extract attribute
    a = split()[0]
    
    # initialize list if it doesn't exist
    sublist = nested.setdefault(a, [])

    sublist.append(a)

print(nested)
```

And the result would look like:
```
{ 
    "attr1": ["attr1 apple 1", "attr1 banana 2"],
    "attr2": ["attr2 grapes 1", "attr2 oranges 2"],
    "attr3": ["attr3 watermelon 0"]
}
```

This has the advantage of doing only `O(N)` iterations. Of course dictionaries themselves have different performance characteristics than lists.