Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grouping elements into a list

I want to group elements into a list of list based on the indexing
Starting with the first position in data, go until the next False. That’s a grouping. Continue until the last element.

data = ['a','b','c','d','e','f'] 
indexer = [True, True, False, False, True, True]

Outcome would be:

[['a','b','c'], ['d'], ['e','f'] ]

Is itertools groupby the right solution? I’m a little confused about how to implement it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply append values to a temporary list and when you reach a False, create a new temporary list, first appending the last one to the resulting list, so basically, create a list after each False, lastly if necessary append the last temporary list to the result:

data = ['a', 'b', 'c', 'd', 'e', 'f']
indexer = [True, True, False, False, True, True]

result, temp = [], []
for value, index in zip(data, indexer):
    temp.append(value)
    if not index:
        result.append(temp)
        temp = []
if temp:
    result.append(temp)

print(result)
# [['a', 'b', 'c'], ['d'], ['e', 'f']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading