首页 > 解决方案 > 在 Python 中使用字符串作为代码进行解码

问题描述

我想要做的是有一个程序来压缩像 AAABBBBCAAAaaDD -> A3B4CA3a2D2 这样的字符串,然后解压缩它。第一个函数已经可以工作,但第二个函数似乎无法看到字符串的第一个元素:

taba = list(string)
decompressed = ''

for i in range(2, len(taba)):
    k = 0
    if str(taba[i]).isnumeric():
        while k < int(taba[i]):
            decompressed += taba[i-1]
            k += 1

输入 = AAABBBBCAAAaaDD,字符串 = A3B4CA3a2D2,解压后的字符串返回 BBBBCAAAaaDD。什么会导致循环不包含 taba[2-1]?

标签: pythonarraysstringpython-3.xloops

解决方案


Pretty sure it's because you're indexing from 2 instead of 0? What was the reasoning behind that? What were you trying to accomplish?


推荐阅读