Search code examples
pythonpython-itertools

How to print with itertools groupby?


I have this code:

from itertools import groupby

text = ["a", "a", "b", "b", "c"]

group = groupby(text)

for k, g in group:
    print(k, end= " ")
    print(sum(1 for _ in g), end=" ")

Example what I need:

A B C
2 2 1

My itertools only shows like this:

A 2 B 2 C 1

Solution

  • You can do it like this which post-processes the results groupby returns to make it easy to get the values needed for each row of the output:

    from itertools import groupby
    
    text = ["a", "a", "b", "b", "c"]
    
    groups = [(k, str(sum(1 for _ in g))) for k, g in groupby(text)]
    a, b = zip(*groups)
    print(' '.join(a))  # -> a b c
    print(' '.join(b))  # -> 2 2 1