如何将列表中相同的元素,合并统计但不改变顺序

img

如图中,l列表中已经有15行,但想要将所有连着的L或D或S合并,如['L', 'L', 'D', 'D', 'D', 'S', 'S', 'S', 'D', 'D']合并为L2D3S3D2的形式。
不是全部重复的统计,而是不改变顺序的

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: YangPC
@time:2021/07/02
@QQ:327844761
@微信公众号:ewbang
"""


def func():
    arr = ['L', 'L', 'D', 'D', 'D', 'S', 'S', 'S', 'D', 'D']
    s = ''.join(arr)
    res = compressString(s)
    print(res)


# 字符串压缩
def compressString(S):
    if not S:
        return ""
    ch = S[0]
    ans = ''
    cnt = 0
    for c in S:
        if c == ch:
            cnt += 1
        else:
            ans += ch + str(cnt)
            ch = c
            cnt = 1
    ans += ch + str(cnt)
    return ans if len(ans) < len(S) else S


if __name__ == '__main__':
    func()



img