如何在 Python 中创建压缩函数?

How can I create compress function in Python?

我需要创建一个名为 StringZip 的函数,它通过用重复次数替换重复的字母来压缩字符串。例如)aaaaabbbbbccccccaaaddddd -> a5b5c6a3d5

我想将此代码更改为函数:

 s = 'aaaaabbbbbccccccaaaddddd'
 result = s[0]  
 count  = 0

 for i in s:
     if i == result[-1]:
         count += 1
     else:
         result += str(count) + i
         count = 1
 result += str(count)

 print(result)

如何使用 def 创建函数?

西尔!使用 def 创建函数的方式如下:

def myFunctionName(myParam, myOtherParam):
   # your function
   return endResult

或者您的情况:

# lower_with_under() is the standard for functions in python
def string_zip(inString):
    s = inString
    result = s[0]  
    count  = 0
    for i in s:
        if i == result[-1]:
            count += 1
        else:
            result += str(count) + i
            count = 1
    result += str(count)
    print(result)

你会这样称呼它:

theResult = myFunctionName(1, 3)

或者您的情况:

print(string_zip("aaaaabbbbbccccccaaaddddd"))

希望对您有所帮助!
顺便说一句,下次,你可以先在 Google 上搜索你想要的东西,然后再在 Stack Overflow 上提问吗?它有助于保持井井有条。谢谢!