简体   繁体   中英

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.

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)

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]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM