Search code examples
pythonpython-3.xpython-itertools

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.


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']]