我是Python新手,所以可能我要求的东西非常简单,但我不能用Python的方式来思考这个问题。你知道吗
我有一个压缩字符串。这个想法是,如果一个角色被重复4-15次,我会做出这样的改变:
'0000' ---> '0|4'
如果超过15次,我使用斜杠和两位数字来表示数量(使用十六进制值):
'00...(16 times)..0' ---> '0/10'
因此,习惯了其他语言,我的方法如下:
def uncompress(line):
verticalBarIndex = line.index('|')
while verticalBarIndex!=-1:
repeatedChar = line[verticalBarIndex-1:verticalBarIndex]
timesRepeated = int(line[verticalBarIndex+1:verticalBarIndex+2], 16)
uncompressedChars = [repeatedChar]
for i in range(timesRepeated):
uncompressedChars.append(repeatedChar)
uncompressedString = uncompressedChars.join()
line = line[:verticalBarIndex-1] + uncompressedString + line[verticalBarIndex+2:]
verticalBarIndex = line.index('|') #next one
slashIndex = line.index('/')
while slashIndex!=-1:
repeatedChar = line[slashIndex-1:slashIndex]
timesRepeated = int(line[slashIndex+1:verticalBarIndex+3], 16)
uncompressedChars = [repeatedChar]
for i in range(timesRepeated):
uncompressedChars.append(repeatedChar)
uncompressedString = uncompressedChars.join()
line = line[:slashIndex-1] + uncompressedString + line[slashIndex+3:]
slashIndex = line.index('/') #next one
return line
我知道这是错误的,因为在Python中字符串是不可变的,我一直在更改行内容,直到不存在“|”或“/”。你知道吗
我知道UserString是存在的,但是我想有一种更简单、更具Pythonish风格的方法,这将是一个很好的学习方法。你知道吗
有什么帮助吗?你知道吗
我见过的最常见的模式是使用字符列表。列表是可变的,正如您上面描述的那样工作。你知道吗
从字符串创建列表
从列表创建字符串
您应该在运行时构建一个子字符串列表,并在末尾加入它们:
使代码与示例字符串一起运行所需的更改:
将
.index()
更改为.find()
。.index()
如果找不到子字符串,则引发异常,.find()
返回-1。你知道吗将
uncompressedChars.join()
更改为''.join(uncompressedChars)
。你知道吗将
timesRepeated = int(line[slashIndex+1:verticalBarIndex+3], 16)
更改为timesRepeated = int(line[slashIndex+1:slashIndex+3], 16)
将
uncompressedChars = []
设置为开头,而不是uncompressedChars = [repeatedChar]
。你知道吗这应该能让它正常工作。有很多地方的代码可以整理和优化,但这是可行的。你知道吗
相关问题 更多 >
编程相关推荐