-1

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
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
  • 1
    Because you exhaust the group-by iterator when you call `list` on it... just turn your list-comprehension into a for-loop and capture the result of the first `list` call with a variable – juanpa.arrivillaga May 23 '18 at 09:12
  • 1
    It's the same problem as [this question](https://stackoverflow.com/questions/50465966/re-using-zip-iterator-in-python-3), but I don't really want to use that as a dupe... – Aran-Fey May 23 '18 at 09:13

1 Answers1

1

Let's take a minimal example:

def a():
    for i in range(10):
        yield i

b = a()
print(list(b))
print(list(b))

output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[]

So you can see you can only call list on a generator once. You need to assign list(g) to a variable first.

Sraw
  • 18,892
  • 11
  • 54
  • 87