使用Python,当输入字符串为aaabbcddddd时,如何将输出字符串打印为->aaa 3bb 2c 1ddddd 5

mnemlml8  于 2023-02-20  发布在  Python
关注(0)|答案(7)|浏览(148)

使用Python,如何将输出字符串打印为-〉aaa 3bb 2c 1ddddd 5当输入字符串为aaabbcddddd时我想将实际字符值和字符在字符串中重复的次数连接起来

def mycode(myString):
    lenstr = len(myString)
    print('length of string is '+str(lenstr));
    for ele in myString:
        count=0
        for character in myString:
            if character == ele:
                count = count+1
        totalstr = ele+str(count)
        
    return totalstr
qco9c6ql

qco9c6ql1#

如果字符串总是像这样排序和分组在一起,那么可以使用collections.Counter来完成。

from collections import Counter
inp = "aaabbcddddd"
counter = Counter(inp)
out = "".join(k * v + str(v) for k,v in counter.items())

或者在一行中:

print(''.join(k * v + str(v) for k,v in Counter(inp).items()))

输出:

aaa3bb2c1ddddd5

您也可以手动执行此操作:

inp = "aaabbcddddd"
last = inp[0]
out = inp[0]
count = 1
for i in inp[1:]:
    if i == last:
        count += 1
    else:
        out += str(count)
        count = 1
        last = i
    out += i
out += str(count)
print(out)
bkhjykvo

bkhjykvo2#

下面是一个使用regex替换回调函数的单行解决方案:

inp = "aaabbcddddd"
output = re.sub(r'((\w)\2*)', lambda m: m.group(1) + str(len(m.group(1))), inp)
print(output)  # aaa3bb2c1ddddd5
du7egjpx

du7egjpx3#

另一句俏皮话:

import itertools

test = 'aaabbcddddd'
out = ''.join(f"{(g := ''.join(ig))}{len(g)}" for _, ig in itertools.groupby(test))
assert out == 'aaa3bb2c1ddddd5'
yh2wf1be

yh2wf1be4#

def char_counter_string(string):
    prev_char = None
    char_counter = 0
    output = ''
    for char_index in range(len(string)+1):
        if char_index == len(string):
            output += str(char_counter)
            break
        if string[char_index] != prev_char and prev_char is not None:
            output += str(char_counter)
            char_counter = 0
        output += string[char_index]
        char_counter += 1
        prev_char = string[char_index]
    return output

if __name__ == '__main__':
    print(char_counter_string('aaabbcddddd'))
46qrfjad

46qrfjad5#

你可以像..

    • 代码:**
    • 时间复杂性:时间复杂度O(n)
input_string="aaabbcddddd"
res=""
count=1

for i in range(1, len(input_string)):
    if input_string[i] == input_string[i-1]:
        count += 1
    else:
        res+=input_string[i-1]*count + str(count)
        count = 1

res+=input_string[-1]*count + str(count)
print(res) #aaa3bb2c1ddddd5
e4eetjau

e4eetjau6#

还有一个办法...
充分披露:...只要字符串为10个或更少,它就会工作。即,如果行中有11个字符,它就不会工作(计数将是错误的)。
它只是一个封装reduce的函数。

from functools import reduce

def char_rep_count(in_string):
    return reduce(
             lambda acc, inp:
               (acc[:-1]+inp+str(int(acc[-1])+1))
                 if (inp==acc[-2])
                 else (acc+inp+"1"),
             in_string[1:],
             in_string[0]+"1"
           )

下面是一些示例输出:

print(char_rep_count("aaabbcdddd"))
aaa3bb2c1dddd4
zaqlnxep

zaqlnxep7#

我认为这满足了简短的要求,也非常快:

s = 'aaabbcddddd'

def mycode(myString):
    if myString:
        count = 1
        rs = [prev := myString[0]]
        for c in myString[1:]:
            if c != prev:
                rs.append(f'{count}')
                count = 1
            else:
                count += 1
            rs.append(prev := c)
        rs.append(f'{count}')
        return ''.join(rs)
    return myString

相关问题