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
Using multiple print statements with transpose
from itertools import groupby
text = ["a", "a", "b", "b", "c"]
group = groupby(text)
# Transpose so we have row 0 with group names, and row 1 with grouping items
transposed = [(k, list(g)) for k, g in group]
for k in transposed:
print(k[0], end = " ")
print()
for k in transposed:
print(sum(1 for _ in k[1]), end=" ")
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
Here is one more alternative:
from itertools import groupby
text = ["a", "a", "b", "b", "c"]
group = groupby(text)
dictionary = {}
for k, g in group:
dictionary[k] = sum(1 for _ in g)
keys = " ".join(list(dictionary.keys()))
values = " ".join(str(v) for v in list(dictionary.values()))
print(keys)
print(values)
I know you asked about itertools.groupby, BUT I would use a Counter for such task:
>>> text = ["a", "a", "b", "b", "c"]
>>> from collections import Counter
>>> c = Counter(text)
>>> print(c)
Counter({'a': 2, 'b': 2, 'c': 1})
>>> headers = c.keys()
>>> values = [str(val) for val in c.values()]
>>> print(' '.join(headers))
a b c
>>> print(' '.join(values))
2 2 1
Since groupby()
does not lend itself to deploying tee()
to make a copy, the best solution seems to be to create a tuple comprehension. Note that we're not interested in the values contained in each group g, so we'll just store the length of the tuple constructed on the fly from the group.
import itertools
text = ["a", "a", "b", "b", "c"]
group = tuple((k,len(tuple(v))) for k,v in itertools.groupby(text))
for t in group:
print(t[0], end= " ")
print()
for t in group:
print(t[1], end=" ")
print()
# a b c
# 2 2 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.