Python,如何在列表末尾不需要额外的空间?

2024-09-27 23:15:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个程序可以压缩一系列字符。你知道吗

def compress(string):
    output = ""
    counter = 1
    firstLoop = True

    for element in range(0, len(string)):
        # if statement checking if current character was last character
        if string[element] == string[element - 1]:
            # if it was, then the character has been written more than one
            # time in a row, so increase counter
            counter = counter + 1
        else:
            # when we detect a new character reset the counter
            # and also record the character and how many times it was repeated
            if not firstLoop:
                output = output + string[element - 1] + str(counter)
        counter = 1

        firstLoop = False
    return output

data = "aaaabbbchhtttttttf"
print(data)

compressedData = compress(data)
print(compressedData)

程序输出:

aaaabbbchhtttttttf
a4b3c1h2t7

所以,它发现有'a'的'4'个条目,所以它写'a4',然后'b3'为b的三个条目

问题是它忘记了字符串末尾的“f1”。我知道这是因为:

output = output + string[element - 1] + str(counter)

由于字符串[element-1]指的是字符串中当前元素之前的位置,因此它永远不会到达“f”所在的最终位置。如果没有'-1',程序将无法工作,因为它无法写入正确的字母。你知道吗

我怎样才能绕过这个问题,使它能够包括f?你知道吗

正确的输出应该是a4b3c1h2t7f1。你知道吗

谢谢:)

编辑:我忘了提到,如果我在“f”后面加上一个额外的字符,比如一个空格,程序就可以工作。但这当然是因为字符串中的最后一个字符只是一个空格而不是一个字母。你知道吗


Tags: the字符串in程序outputdatastringif
3条回答

您可以使用^{}^{}来完成这一切,并避免对索引进行计数和跟踪:

from itertools import groupby

def compress(string):
    return ''.join(k + str(sum(1 for _ in g)) for k, g in groupby(string))

>>> compress("aaaabbbchhtttttttf")
'a4b3c1h2t7f1'

您可以使其更简单,并在末尾添加一个字符:

def compress(string):
    output = ""
    counter = 0
    string = string + '|'
    for element in range(0, len(string)):
        # if statement checking if current character was last character
        if string[element] == string[element - 1]:
            # if it was, then the character has been written more than one
            # time in a row, so increase counter
            counter = counter + 1
        elif element != len(string):
            output = output + string[element - 1] + str(counter)
            counter = 1
    return output[2:]

data = "aaaabbbchhtttttttf"
print(data)

compressedData = compress(data)
print(compressedData)
def compress(string):
output = ""
counter = 1

for element in range(1, len(string)):
    # if statement checking if current character was last character
    if string[element] == string[element - 1]:
        # if it was, then the character has been written more than one
        # time in a row, so increase counter
        counter = counter + 1
    else:
        # when we detect a new character reset the counter
        # and also record the character and how many times it was repeated
        output = output + string[element - 1] + str(counter)
        counter = 1

return output + string[-1] + str(counter)

还要注意的是,您需要开始计算形式1而不是0,并去掉firstLoop

相关问题 更多 >

    热门问题