Python计数字符串中的字符数

Aru*_*run 1 python list-comprehension python-3.x

输入:

abbbbccdddaaabbbbeeff
Run Code Online (Sandbox Code Playgroud)

输出:

ab4c2d3a3b4e2f2
Run Code Online (Sandbox Code Playgroud)

我已经尝试过如下

string = 'abbbbccccd'

strList = list(string)
sum = 0

for i , s in enumerate(string):
    # print (strList[i],strList[i+1])

    if strList[i] == strList[i+1]:
        sum = sum + 1
        print(strList[i],'****',sum )

    else:
        sum = sum + 1
        print(strList[i],'****',sum )
        sum = 0
Run Code Online (Sandbox Code Playgroud)

但是无法打印列表中的最后一个元素。

有没有使用任何内置函数的更好方法?

编辑:我想了解打印abb4c2的逻辑。这就是为什么我提到没有任何内置函数的原因。如果逻辑可以理解,则可以使用内置函数。

Jea*_*bre 6

在这些问题中,请始终保持当前状态(当前字符和当前计数)。无需索引,逻辑更​​简单。

最后,不要忘记“刷新”当前循环数据,否则您会错过最后一次迭代。

我的建议:

s = "abbbbccdddaaabbbbeeff"

result = []

current = None
current_count = 0


for c in s:
    if current == c:
        current_count += 1
    else:
        if current_count > 1:
            result.append(str(current_count))
        current_count = 1
        current = c
        result.append(c)

# don't forget last iteration count
if current_count > 1:
    result.append(str(current_count))

print("".join(result))
Run Code Online (Sandbox Code Playgroud)

印刷品:

ab4c2d3a3b4e2f2
Run Code Online (Sandbox Code Playgroud)

好的,我知道"".join(result)调用一个内置函数,但这是最有效的方法。您不想一个接一个地追加字符来从列表中创建字符串。

一旦证明您掌握了这些算法,就可以使用内置函数itertools.groupby来完成这些工作。它更快,没有错误(甚至更好:另一个答案