我正在做一个练习,我们将通过列表对数据压缩进行建模。假设我们得到了一个列表:[4,4,4,4,4,4,2,9,9,9,9,9,5,5,4,4]我们应该应用游程编码,并获得一个新的[4,6,2,1,9,5,5,2,4,2]列表,其中它显示了有多少4 (6) 2(1)9 (5) 5 (2),依此类推。紧跟在整数旁边。
到目前为止,我有以下代码,但是我遇到了一个语义错误,并且不确定如何修复它:
def string_compression(List):
newlist=[]
counter=0
x=0
for elm in List:
prev_item= List[x-1]
current_item=List[x]
if prev_item == current_item:
counter+=1
else:
newlist+=[current_item]+[counter]
counter=0附言:我还是个初学者,所以如果这是一个“愚蠢”的问题,我道歉!如果能帮上忙我会很感激的。
发布于 2016-10-12 14:12:23
你的代码对所有这些计数器来说真的很混乱。您需要做的是按照定义的方式实现算法。您只需要一个索引i,它可以跟踪您当前所处的列表位置,并在每个步骤中将该数字与前一个数字进行比较。
发布于 2016-10-12 16:10:21
您在正确的轨道上,但是使用基于索引的循环会更容易:
def rle_encode(ls):
# Special case: the empty list.
if not ls:
return []
result = []
# Count the first element in the list, whatever that is.
count = 1
# Loop from 1; we're considering the first element as counted already.
# This is safe because we know that the list isn't empty.
for i in range(1, len(ls)):
if ls[i] == ls[i - 1]:
count += 1
else:
# Store the last run.
result.append(ls[i - 1])
result.append(count)
# Count the current number.
count = 1
# Add the last run since we didn't get a chance to in the loop.
result.append(ls[-1])
result.append(count)
return resulthttps://stackoverflow.com/questions/39991511
复制相似问题