为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

守着一只汪 2021-06-21 15:07:42
我编写了一个可以压缩字符序列的程序。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 outputdata = "aaaabbbchhtttttttf"print(data)compressedData = compress(data)print(compressedData)程序输出:aaaabbbchhtttttttfa4b3c1h2t7因此,它发现 'a' 有 '4' 个条目,所以它写入 'a4',然后为 b 的三个条目写入 'b3'。问题是它忘记了字符串末尾的“f1”。我知道这是因为这条线:output = output + string[element - 1] + str(counter)由于 string[element-1] 指的是字符串中当前元素之前的位置,因此,它永远不会到达 'f' 所在的最终位置。如果没有“-1”,程序将无法运行,因为它没有写出正确的字母。我怎样才能解决这个问题并使它能够包含 f?正确的输出应该是 a4b3c1h2t7f1。谢谢 :)编辑:我忘了提到如果我在 'f' 后面包含一个额外的字符,例如只是一个空格,程序就可以工作。但这当然是因为我的字符串中的最后一个字符只是一个空格而不是一个字母。
查看完整描述

3 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

你可以让它更简单并在最后添加一个字符:


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)


查看完整回答
反对 回复 2021-06-29
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

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


查看完整回答
反对 回复 2021-06-29
  • 3 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信