伙计们,我正在尝试通过输入a4b2c1a2d3
获得aaaabbcaaddd
的输出。我认为以下代码的问题是我实现先前计数器的方式。 index > 0:
有问题吗?
string1 = "aaaabbcaaddd"
previous = ""
finalstr = ""
finalint = 1
for index, val in enumerate(string1):
if index > 0:
previous = string1[index - 1]
if previous == val:
finalint += 1
else:
finalstr += previous + str(finalint)
finalint = 1
print(finalstr)
#outputs "a4b2c1a2"
答案 0 :(得分:2)
正如我在评论中所说,您忘了在循环之后 添加最后一个计数:
finalstr += previous + str(finalint)
但是,除非您将其作为分配的作业进行,否则,存在一种更为紧凑的解决问题的方法:
from itertools import groupby
''.join(char + str(len(list(group))) for char,group in groupby(string1))
#'a4b2c1a2d3'
您自己的代码可以不用索引而重写(它们总是会引起麻烦):
cnt = 1
finalstr = ''
for x,y in zip(string1, string1[1:]):
if x==y:
cnt += 1
else:
finalstr += x + (str(cnt) if cnt > 1 else '')
cnt = 1
finalstr += x + (str(cnt) if cnt > 1 else '')
finalstr
#'a4b2ca2d3'
答案 1 :(得分:2)
这称为“行程编码”。在Python库more-itertools中,有一个函数可以进行这种编码:
>>> from more_itertools import run_length
...
... string1 = "aaaabbcaaddd"
... list(run_length.encode(string1))
[('a', 4), ('b', 2), ('c', 1), ('a', 2), ('d', 3)]
我们可以通过将其展平并对其进行字符串化来获得所需的输出。
>>> list(flatten(run_length.encode(string1)))
['a', 4, 'b', 2, 'c', 1, 'a', 2, 'd', 3]
>>> list(map(str, flatten(run_length.encode(string1))))
['a', '4', 'b', '2', 'c', '1', 'a', '2', 'd', '3']
>>> ''.join(map(str, flatten(run_length.encode(string1))))
'a4b2c1a2d3'
答案 2 :(得分:0)
如果有人对我的解决方案感到好奇(在DYZ的帮助下)
string1 = "aaaabbcaaddd"
finalstr = ""
previous = ""
finalint = 0
for c, v in enumerate(string1):
if c > 0:
previous = string1[c - 1]
if previous == v:
finalint += 1
else:
finalstr += previous + str((finalint) if finalint > 1 else '')
finalint = 1
finalstr += previous + str((finalint) if finalint > 1 else '')
print(finalstr)
#outputs a3b2ca2d3
答案 3 :(得分:0)
from itertools import groupby
string1 = "aaaabbcaaddd"
string2 = ''
for c, g in groupby(string1):
string2 += '%s%d'%(c, len(list(g)))
答案 4 :(得分:0)
您可以使用itertools groupby进行相同的操作。
from itertools import groupby
string1 = 'aaaabbcaaddd'
result = [[k, len(list(g))] for k, g in groupby(string1)]
final = "".join([i[0]+str(i[1]) for i in result])
final
output: #'a4b2c1a2d3'