我有包含相同字符 block 的字符串,例如 '1254,,,,,,,,,,,,,,,,982'。我的目标是将其替换为类似“1254(,16)982”的内容,以便可以重建原始字符串。如果有人能指出我正确的方向,将不胜感激
最佳答案
您正在寻找 run-length encoding : 这是一个松散地基于 this one 的 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)
以你的例子为例:
print runlength_enc("1254,,,,,,,,,,,,,,,,982")
# ['1254', (',', 16), '982']
print runlength_decode(runlength_enc("1254,,,,,,,,,,,,,,,,982"))
# 1254,,,,,,,,,,,,,,,,982
(请注意,只有当您的字符串中有很长的运行时,这才会有效)。
关于python - 如何通过删除python中的重复项进行压缩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13122575/