对字符串进行RLE压缩,将相邻的相同字符,用计数值和字符值来代替。例如:aaabccccccddeee,则可用3a1b6c2d3e来代替。
通过对相邻的字符分组实现:
def run_length_encoding(seq): from itertools import groupby cc = [[sum(1 for _ in g), c] for c, g in groupby(seq)] print(cc) return cc
cc =run_length_encoding("aaabccccccddeee")
print(cc)
运行结果如下所示: