I have a sequence in which I want to count runs (ie consecutive identical entries), and return a list of the length of the runs. The code below
from itertools import groupby
S = [1,1,1,2,3,3,4,5,5]
grouped_S = [sum(1 for i in group) for key,group in groupby(S)]
Results, as it should, in
[3, 1, 2, 1, 2]
But I want to ignore spells that are 1-long, and get output just [3,2,2]. This
grouped_S = [sum(1 for i in group) for key,group in groupby(L) if sum(1 for i in g) >1]
gives
[0,0,0].
It clearly knows I want just the three sequences > 1, but won't return their length.
I don't understand this behavior, could someone please explain? Right now my solution is:
S = [sum(1 for i in g) for k,g in groupby(S)]
S = [i for i in S if i != 1]
and it works, but there has to be a pythonic one-liner I can't figure out.
As the documentation of groupby
points out:
The returned group is itself an iterator that shares the underlying iterable with
groupby()
.
You can only iterate an iterator once, which you're doing in the if
; there's nothing left in the iterator to sum
again then. It would be far easier to simply filter the 1
s out of the result:
grouped_S = list(filter(lambda s: s > 1, (sum(1 for i in g) for k,g in groupby(S))))
You could very well save your variable in a list comprehension and then check it afterwards:
from itertools import groupby
S = [1,1,1,2,3,3,4,5,5]
grouped_S = [group
for k,g in groupby(S)
for group in [sum(1 for i in g)]
if group > 1]
print(grouped_S)
This yields
[3, 2, 2]
as @deceze already pointed your variable g
is an iterator:
from the docs :
iterator
An object representing a stream of data. Repeated calls to the iterator's next () method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its next () method just raise StopIteration again print([len(g) for k, [*g] in groupby(S) if len(g) > 1])
you can make your g
variable a list by using iterable unpacking operator :
print([len(g) for k, [*g] in groupby(S) if len(g) > 1])
output:
[3, 2, 2]
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.