简体   繁体   English

如何在 Python 中创建压缩 function?

[英]How can I create compress function in Python?

I need to create a function called StringZip that compresses a string by replacing repeated letters with number of repeats.我需要创建一个名为 StringZip 的 function,它通过用重复次数替换重复的字母来压缩字符串。 Ex) aaaaabbbbbccccccaaaddddd -> a5b5c6a3d5例如)aaaabbbbbccccccaaaddddd -> a5b5c6a3d5

I want to change this code into function:我想将此代码更改为 function:

 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)

How can I create function using def?如何使用 def 创建 function?

syl!西尔! The way that you can create a function with def is like this:使用def创建 function 的方式如下:

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

Or in your case:或者在你的情况下:

# 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)

And you would call it like:你会这样称呼它:

theResult = myFunctionName(1, 3)

Or in your case:或者在你的情况下:

print(string_zip("aaaaabbbbbccccccaaaddddd"))

I hope this helps!我希望这有帮助!
By the way, next time, can you try searching on Google for what you want before asking it on Stack Overflow?顺便说一句,下一次,你可以先在 Google 上搜索你想要的东西,然后再在 Stack Overflow 上提问吗? It helps keep it organized.它有助于保持井井有条。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM