I'm trying to create a run-len-encoding in Python using the following code which seem to work
from itertools import groupby
a = [0,0,0,1,1,0,1,0,1, 1, 1]
[list(g) for k, g in groupby(a)]
## [[0, 0, 0], [1, 1], [0], [1], [0], [1, 1, 1]]
But when I put g
in an if
statement, it disappears
[list(g) if len(list(g)) > 0 else 0 for k, g in groupby(a)]
## [[], [], [], [], [], []]
k
on the other hand, doesn't seem to be effected by the if
statement
[k if k > 0 and k == 1 else 0 for k, g in groupby(a)]
## [0, 1, 0, 1, 0, 1]
I need to extract g
using the if
statement for some future recording I'm trying to do, e.g.,
import numpy as np
[list(np.repeat(1, len(list(g)))) if len(list(g)) > 1 and k == 1 else list(np.repeat(0, len(list(g)))) for k, g in groupby(a)]
So my question is why it happens (kind of new to Python) and is there (I'm sure there is) to overcome this
EDIT
This is not directly related to the question itself, but I've eventually built my rle/inverse.rle
using a for
loop over the groups in groupby
def rle (a):
indx = 0
for k, g in groupby(a):
g_len = len(list(g))
if g_len == 1 and k == 1:
a[indx:(indx + g_len)] = [0]
indx += g_len