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

标签 python algorithm list

我写了一个可以压缩字符序列的程序。

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”,然后为 b 的三个条目写入“b3”。

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

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

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

我怎样才能解决这个问题并使其能够包含 f?

正确的输出应该是a4b3c1h2t7f1。

谢谢:)

编辑:我忘了说,如果我在“f”之后添加一个额外的字符(例如空格),程序就可以运行。但这当然是因为我的字符串中的最后一个字符只是一个空格而不是一个字母。

最佳答案

您可以使用 itertools.groupby 完成这一切和 sum并避免所有计数和跟踪索引:

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'

关于Python,如何在列表末尾不需要额外的空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52520457/

相关文章:

python-3.x - 有没有办法删除Python字符串中直到某个元素的元素?

python - 如何获取列中的最新时间戳?

python - 计算向量的任何一对 2 元素之差的算法

java - 如何读取堆栈的所有元素而不弹出它们?

c++ - 按照每对权重之和的顺序,高效地计算两个加权集合中的对

list - Salesforce 顶点触发列表中的重复 ID

python - 如何在特定范围内规范化 csv 文件中的数据

python - AxesGrid 与 imshow : do plots have to have the same extent?

python - 模板中的 Flask matplotlib 图形

c++ - C++ list.erase(it, it) 是否删除某些东西?在哪里可以找到好的引用资料?