Python 用数字编码字符串中的重复字母

Python 用数字编码字符串中的重复字母,python,Python,字符串“abc”必须变成“a1b1c1”。 字符串“aaabcca”-“a3b1c2a1” 我编写了python函数,但它没有添加最后一个字母,“abc”只是“a1b1” string = "aaabbcc" coded = '' if len(string) == 0: print('') else: count = 1 #start with the first char, not zero! prev = string[0] for i in range(1,len(

字符串“abc”必须变成“a1b1c1”。 字符串“aaabcca”-“a3b1c2a1”

我编写了python函数,但它没有添加最后一个字母,“abc”只是“a1b1”

string = "aaabbcc"
coded = ''
if len(string) == 0:
   print('')
else:
  count = 1   #start with the first char, not zero!
  prev = string[0]
  for i in range(1,len(string)):
    current = string[i]
    if current == prev:     
       count +=1
    else:              
      coded += prev
      coded += str(count)
      count = 1
      prev = current
      print("coded string: " + coded)
print(coded)
使用

有关
groupby
生成内容的详细信息:

>>> groups = groupby(s)
>>> [(char, list(group)) for char, group in groups]
[('a', ['a', 'a', 'a']), ('b', ['b']), ('c', ['c', 'c']), ('a', ['a'])]

您忘记显式添加最后一次迭代

string = "aaabb"
coded = ''
if len(string) == 0:
   print('')
else:
  count = 1   #start with the first char, not zero!
  prev = string[0]
  for i in range(1,len(string)):
    current = string[i]
    if current == prev:     
       count +=1
    else:              
      coded += prev
      coded += str(count)
      count = 1
      prev = current
coded += prev       # these two
coded += str(count) # lines

print(coded)
不过,我更喜欢不太复杂的循环:

string = "aaabbcc"
coded = ''
while string:
    i = 0
    while i < len(string) and string[0] == string[i]:
        i += 1
    coded += string[0]+str(i)
    string = string[i:]

print(coded)
string=“aaabbcc”
编码=“”
而字符串:
i=0
而i
如果您想知道为什么您的代码不起作用,或者您不想使用任何外部库,这里是您的代码的工作版本

string = "aaabbcc"
coded = ''

if len(string) == 0:
   print('')

else:
  count = 0
  prev = string[0]
  for i in range(1,len(string)):
    current = string[i]
    count +=1

    if current != prev:
      coded += prev
      coded += str(count)
      count = 0

    prev = current

  coded += current
  coded += str(count+1)

print(coded) # -> a3b2c2
一些正则表达式魔术:

输出:

a3w1b3c2d5

详情:

正则表达式模式:

  • ()
    -将字符
    (任何字符)捕获到第一个捕获的组中
  • \1*
    -匹配零个或多个连续的
    \1
    ,这是对第一个捕获的组值的引用(匹配可能相同字符的序列)
替换:

  • m.group(1)
    -包含第一个匹配的组值
  • str(len(m.group())
    -获取匹配的整个字符序列的长度

提示:itertools.groupby?输入的字母可能未排序,对吗
wwaaadvc
@RomanPerekhrest,yeshow你会写“while len(string)”吗?@ERJAN:uhm。用我的键盘?你觉得有什么问题吗?我确实测试了我的代码。python不允许这样吗?作为条件?len(string)=真?这是一个条件吗?“测试表达式,如果为真,则执行第一个套件”
len(字符串)
是一个数字。。。啊–你不需要
len(string)
“达到每日投票限制”–该死。我一天后回来。邪恶。@usr2564301,没问题)@RomanPerekhrest,你能用sub()详细解释一下这个表达式吗?
import re

s = 'aaawbbbccddddd'
counts = re.sub(r'(.)\1*', lambda m: m.group(1) + str(len(m.group())), s)
print(counts)
a3w1b3c2d5