Python 计算字符串的运行长度编码

Python 计算字符串的运行长度编码,python,character-encoding,Python,Character Encoding,例如,如果字符串有“xxxyz”,则输出为3x2y1z 我不知道如何去做这个问题,我尝试了多种方法,但似乎无法接近我想要的输出 s = input("Please type a sentence or word: ") i = 0 count = 1 while len(s) <=i: if s[i] == s[i+1]: count = count+1 s1 = count + s[i] s=input(“请键入一个句子或单词:”) i=0

例如,如果字符串有“xxxyz”,则输出为3x2y1z 我不知道如何去做这个问题,我尝试了多种方法,但似乎无法接近我想要的输出

s = input("Please type a sentence or word: ")
i = 0
count = 1
while len(s) <=i:
    if s[i] == s[i+1]:
         count = count+1
         s1 = count + s[i]
s=input(“请键入一个句子或单词:”)
i=0
计数=1

而len(s)这是一个你可以尝试的版本。它用于同时迭代输入字符串的两个相邻字符,并能够打印循环结束时剩下的内容:

strg = "xxxyyz"

mult = 1
lgth = len(strg)
for i, (prev, nxt) in enumerate(zip(strg, strg[1:])):
    if prev != nxt:
        print('{}{}'.format(mult, prev), end='')
        mult = 1
    else:
        mult += 1
    if i == lgth-2:  # print what is left at the end of the string
        print('{}{}'.format(mult, nxt))
mult = 1
for prev, nxt in zip(strg, strg[1:]):
    if prev != nxt:
        print('{}{}'.format(mult, prev), end='')
        mult = 1
    else:
        mult += 1
print('{}{}'.format(mult, nxt))
循环将被忽略

i (prev, nxt)
-------------
0 ('x', 'x')
1 ('x', 'x')
2 ('x', 'y')
3 ('y', 'y')
...

实际上不需要
枚举
<代码>nxt
可在循环后访问:

strg = "xxxyyz"

mult = 1
lgth = len(strg)
for i, (prev, nxt) in enumerate(zip(strg, strg[1:])):
    if prev != nxt:
        print('{}{}'.format(mult, prev), end='')
        mult = 1
    else:
        mult += 1
    if i == lgth-2:  # print what is left at the end of the string
        print('{}{}'.format(mult, nxt))
mult = 1
for prev, nxt in zip(strg, strg[1:]):
    if prev != nxt:
        print('{}{}'.format(mult, prev), end='')
        mult = 1
    else:
        mult += 1
print('{}{}'.format(mult, nxt))

使用集合。计数器

import collections
collections.Counter(your_string)

非常感谢,现在我只需要理解enumerate和zip的含义,但它有助于清除所有其他情况!抱歉,这是另一个问题,当我输入xxxyzz时,输出为3x2y1y而不是3x2y1z,我尝试更改“if I==lgth-2”并与其他部分一起玩,但不确定为什么它会给出y而不是z。。。我得到了输入的
'xxxyyz'
'3x2y2z'
。对不起,我只是小心地重新键入了它,这代表我是一个错误!