A problem with itertools.groupby
ast
ast at invalid
Fri Dec 17 03:25:03 EST 2021
Python 3.9.9
Hello
I have some troubles with groupby from itertools
from itertools import groupby
for k, grp in groupby("aahfffddssssnnb"):
print(k, list(grp))
print(k, list(grp))
a ['a', 'a']
a []
h ['h']
h []
f ['f', 'f', 'f']
f []
d ['d', 'd']
d []
s ['s', 's', 's', 's']
s []
n ['n', 'n']
n []
b ['b']
b []
It works as expected.
itertools._grouper objects are probably iterators
so they provide their datas only once. OK
but:
li = [grp for k, grp in groupby("aahfffddssssnnb")]
list(li[0])
[]
list(li[1])
[]
It seems empty ... I don't understand why, this is
the first read of an iterator, it should provide its
data.
This one works:
["".join(grp) for k, grp in groupby("aahfffddssssnnb")]
['aa', 'h', 'fff', 'dd', 'ssss', 'nn', 'b']
regards
More information about the Python-list
mailing list