James Schinner
James Schinner

Reputation: 1579

Python itertools.groupby length key?

using python 3.6

Is there a way to return the length of a groupby generator as its key?

so this:

from itertools import groupby

x = [1,1,1,1,1,
     2,2,2,2,
     3,3,3,
     4,4,
     5]

for key, group in groupby(x): # Some lambda function here?
    print(key,'|', group)

would output:

5 | <itertools._grouper object at 0x0000016D0FFD45C0>
4 | <itertools._grouper object at 0x0000016D0FFD4668>
3 | <itertools._grouper object at 0x0000016D0FFD4400>
2 | <itertools._grouper object at 0x0000016D0FFD45C0>
1 | <itertools._grouper object at 0x0000016D0FFD4668>

Cheers.

Upvotes: 1

Views: 1598

Answers (2)

cs95
cs95

Reputation: 402814

No, that isn't possible. But you could always convert the group to a list and print its length:

for key, group in groupby(x): 
    sub_list = list(group)
    print(len(sub_list),'|', sub_list)

Output:

5 | [1, 1, 1, 1, 1]
4 | [2, 2, 2, 2]
3 | [3, 3, 3]
2 | [4, 4]
1 | [5]

Upvotes: 1

Ofer Sadan
Ofer Sadan

Reputation: 11942

If you don't mind loading the generators into lists, you could do that and check their length

for key, group in groupby(x):
    l = list(group)
    print(len(l))
    do_something_else_with_list(l)

If you meant that you want to check how long the groupby itself is, the you can do the same with that:

groupby_list = list(groupby(x))
print(len(groupby_list))

Just be careful, once you turned a generator into a list the generator itself cannot be iterated over again, and you should only use the list (or re-create the generator)

Upvotes: 1

Related Questions