我正在进行一项练习,我们将通过列表对数据压缩进行建模。说我们得到了一个清单:[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' s(1)9' s(5)5&# 39; s(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
P.S我还是初学者,所以如果这是一个“愚蠢的”,我会道歉。题!我真的很感激一些帮助。
答案 0 :(得分:0)
您的代码对所有这些计数器都非常困惑。您需要做的是实现定义的算法。您只需要一个索引i
,它可以跟踪您当前所在列表的位置,并在每个步骤中将该数字与之前的数字进行比较。
答案 1 :(得分:0)
您已走上正轨,但使用基于索引的循环会更容易:
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 result