考虑“字符串”(将其视为数字数组)
0 0 1 8 8 8 1 0
RLE(“groupby”)是:
[(0,2), (1, 1), (8,3), (1, 1), (0, 1)]
然后,我们用前面元素的运行长度之和来丰富上述RLE。
因此,上述的丰富版本变为:
[(0, (0,2)), (0+2, (1, 1)), (0+2+1, (8,3)), (0+1+2+3, (1, 1)), (0+1+2+3+1, (0, 1))]
“字符串”分为1:
0 0 , 8 8 8 , 0
RLE分裂为1
[(0,2)] , [(8,3)] , [(0, 1)]
“字符串”拆分为8:
0 0 1 , , , 1 0
RLE分裂为8
[(0,2), (1, 1)] , , , [(1, 1), (0, 1)]
注意:在我的例子中,我引用了“RLE拆分Z”列表而没有丰富它们。事实并非如此。我把它们留下来以减少混乱。例如,“RLE拆分1”应该被视为:
[(0, (0,2))] , [(0+2+1, (8,3))] , [(0+1+2+3+1, (0, 1)]
如何在Z 上实现“RLE分割”(= 1,8;在这种情况下)
没有空数组(拆分后)。
也许是一个聪明的名单comp。? (使用嵌套嵌套的for循环似乎更容易解决)
答案 0 :(得分:1)
import itertools
def get_rle(list_of_digits, split_on=None):
count = 0
rle = []
active_group = []
rle_app = rle.append
for item, group in itertools.groupby(list_of_digits):
L = len(list(group))
if item == split_on:
rle_app(active_group)
active_group = []
else:
active_group.append((count, (item, L)))
count += L
rle_app(active_group)
return rle
list_of_digits = map(int, '0 0 1 8 8 8 1 0'.split())
print get_rle(list_of_digits)
print get_rle(list_of_digits, 8)
print get_rle(list_of_digits, 1)
aaron@aaron-laptop:~/code/tmp$ python rle.py
[[(0, (0, 2)), (2, (1, 1)), (3, (8, 3)), (6, (1, 1)), (7, (0, 1))]]
[[(0, (0, 2)), (2, (1, 1))], [(6, (1, 1)), (7, (0, 1))]]
[[(0, (0, 2))], [(3, (8, 3))], [(7, (0, 1))]]
答案 1 :(得分:1)
只是为了表明方式,我强烈建议你不要使用这个
“优雅”丑陋的方式:
>>> data
[0, 0, 1, 8, 8, 8, 4, 4, 1, 0]
>>> def fromDataToSplitRLE(dat,n):
RLE=[(k,len(tuple(g))) for k,g in itertools.groupby(dat)]
tmp=tuple(zip(*RLE))
return [list(g) for k,g in itertools.groupby((zip((sum(tmp[1][:i]) for i in range(len(tmp[1]))) ,(zip(*tmp)))),lambda x:x[1][0]!=n) if k]
>>> fromDataToSplitRLE(data,1)
[[(0, (0, 2))], [(3, (8, 3)), (6, (4, 2))], [(9, (0, 1))]]