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
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...
Answer
#1: Initial revision
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.