我正在尝试使用下面的代码在python中创建run-len编码
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]]
但当我把
g
在一个
if
声明,它消失了
[list(g) if len(list(g)) > 0 else 0 for k, g in groupby(a)]
## [[], [], [], [], [], []]
k
另一方面,似乎不受
如果
陈述
[k if k > 0 and k == 1 else 0 for k, g in groupby(a)]
## [0, 1, 0, 1, 0, 1]
我需要提取
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)]
所以我的问题是为什么它会发生(对python来说是新的),并且是否有(我确信有)来克服这个问题
编辑
这与问题本身没有直接关系,但我最终建立了
rle/inverse.rle
使用
for
循环访问组
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