如何通过删除python中的重复项来压缩?

Dam*_*ish 3 python compression string whitespace

我有相同字符的字符串,例如'1254 ,,,,,,,,,,,,,,,, 982'.我打算做的是用'1254(,16)982'中的某些东西替换它,以便可以重建原始字符串.如果有人能指出我正确的方向,将非常感激

Dav*_*son 7

你要找的行程编码:这里是松散的,基于Python实现这一个.

import itertools

def runlength_enc(s):
    '''Return a run-length encoded version of the string'''
    enc = ((x, sum(1 for _ in gp)) for x, gp in itertools.groupby(s))
    removed_1s = [((c, n) if n > 1 else c) for c, n in enc]
    joined = [["".join(g)] if n == 1 else list(g)
                    for n, g in itertools.groupby(removed_1s, key=len)]
    return list(itertools.chain(*joined))

def runlength_decode(enc):
    return "".join((c[0] * c[1] if len(c) == 2 else c) for c in enc)
Run Code Online (Sandbox Code Playgroud)

对于你的例子:

print runlength_enc("1254,,,,,,,,,,,,,,,,982")
# ['1254', (',', 16), '982']
print runlength_decode(runlength_enc("1254,,,,,,,,,,,,,,,,982"))
# 1254,,,,,,,,,,,,,,,,982
Run Code Online (Sandbox Code Playgroud)

(请注意,只有在字符串中运行很长时才会有效).