[英]How can I create compress function in Python?
我需要創建一個名為 StringZip 的 function,它通過用重復次數替換重復的字母來壓縮字符串。 例如)aaaabbbbbccccccaaaddddd -> a5b5c6a3d5
我想將此代碼更改為 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)
如何使用 def 創建 function?
西爾! 使用def
創建 function 的方式如下:
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 上提問嗎? 它有助於保持井井有條。 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.