游程编码Python [英] Run Length Encoding Python
问题描述
我遇到的问题是:
编写一个函数,该函数将一个字符列表作为参数,并返回一个反映该列表的游程长度编码的列表.返回列表中的元素遵循以下模式:偶数索引包含字符,奇数索引包含连续重复字符的次数.将您的函数命名为runLengthEncoding(myList).
Write a function that takes, as an argument, a list of characters and returns a list reflecting the run-length encoding of that list. The elements in the returned list follow the following pattern: the even indices contain the characters and the odd indices contain the number of times the character is repeated consecutively. Name your function runLengthEncoding(myList).
例如, runLengthEncoding([aaabbccd])
应该返回 [a,3,b,2,c,2,d,1]
.
这里是我所拥有的,但我不知道出了什么问题:
Here is what I have, but I can't figure out what is wrong:
def runLengthEncoding(myList):
aList = []
count = 1
for i in range(0, len(myList)):
if myList[i] == myList[i - 1]:
count = count + 1
else:
aList.append((count, myList[i - 1]))
count = 1
if i == len(myList) - 1:
aList.append((count, myList[i]))
return aList
推荐答案
您几乎拥有它,但是需要进行一些更改.调用 runLengthEncoding([aaabbccd])
将不起作用,因为它将 aabbccd
作为变量而不是字符串进行调用.如果用引号将方括号替换,则将以字符串形式提供预期的输入(在python中也称为字符列表).
You almost had it, there are a couple of changes necessary however. Calling runLengthEncoding([aaabbccd])
will not work as it is calling aabbccd
as a variable, not as a string. If you replace the square brackets with quotation marks, you will have the intended input as a string (also known in python as a list of chars).
此外,根据您对函数输出格式的要求,您当前正在输出一个元组列表,而不是一个带有其计数的char的向上列表.要按照问题中的指定输出,您可以将 aList.append((count,myList [i-1]))
行更改为:
Also, depending on how picky you have to be on the format of the output of the function, you are currently outputting a list of tuples, instead of a straight up list of the chars with their counts. To output this as specified in the question, you can change your aList.append((count, myList[i-1]))
lines to be:
aList.append(myList[i-1])
aList.append(count)
最后,您发布的代码唯一的错误是您希望for循环从1而不是0开始.这意味着 i-1
将从0开始-1.这是工作的修改后的代码:
And finally, the only thing wrong with the code you posted was that you want your for loop to start at 1 rather than 0. This will mean that the i-1
will start at 0 instead of -1. Here is the working modified code:
def runLengthEncoding(myList):
aList = []
count = 1
for i in range(1, len(myList)):
if myList[i] == myList[i - 1]:
count = count + 1
else:
aList.append((count, myList[i - 1]))
count = 1
if i == len(myList) - 1:
aList.append((count, myList[i]))
return aList
这篇关于游程编码Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!