我有一个函数调用函数rlEncode,该函数应该获取数据列表并对其进行压缩,以便计算行中有多少个值,并输出例如[1,5,3,2,5] ,6]等。但是当我运行它时,只是一次又一次地放置[1,5]而不是将n值移动到列表中的那么多空格。如何从函数rlEncode中获取n值以用于其他函数?
def rlEncode(n, z, data_list):
while data_list[n] == data_list[n+1]:
z = z + 1
n = n + 1
while data_list[n] != data_list[n+1]:
return n
return z
def unitTest( ):
c = 0
n = 0
z = 1
data_list = [1,1,1,1,1,3,3,5,5,5,5,5,5,6,8,8,1,1,1,5,5,5,5,13,14, 14]
compress_list = [ ]
while c < (len(data_list)):
n = rlEncode(n, 1, data_list)
z = rlEncode(0, z, data_list)
rlEncode(0, 1, data_list)
compress = [data_list[n], z]
c = c + 1
compress_list = compress_list + compress
print(compress_list)
n = n+1
答案 0 :(得分:1)
Python按值传递不可变对象。请参阅上一个答案:How do I pass a variable by reference?
在您的情况下,最简单的解决方案是让内部函数将n
的值返回到外部函数,该函数将其分配给其本地n
。
compress
是一个可变的列表,因此您可以使用+=
来改变列表,而不是创建新的局部变量。
我还对列表长度添加了一个检查,否则对n+1
的引用将导致IndexError。
我也认为你不需要rlEncode中的第二个while
循环,但我会把它留给你来解决......:)
def rlEncode(n, z, data_list, compress):
while (n < len(data_list)-1) and (data_list[n] == data_list[n+1]):
z = z + 1
n = n + 1
while (n < len(data_list)-1) and (data_list[n] != data_list[n+1]):
compress += [data_list[n], z]
n = n + 1
return n
def unitTest(data_list):
c = 0
n = 0
compress = []
while c < (len(data_list)):
n = rlEncode(n, 1, data_list, compress)
c = c + 1
return ('list: ', data_list, "compressed list: ", compress)
sample_data = [1,1,1,1,1,3,3,5,5,5,5,5,5,6,8,8,1,1,1,5,5,5,5,13, 14, 14]
unitTest(sample_data)
答案 1 :(得分:0)
我喜欢递归地做这些事情。 Python对递归并不好,但我想看看它是如何完成的,所以我想我会分享:
def compress(lst):
if not lst:
return []
current = lst[0]
result = compress(lst[1:])
if not result:
# item is last
return [(1, current)]
nxt = result[0][1]
if current == nxt:
# items is same as next
return [(result[0][0] + 1, current)] + result[1:]
# different items
return [(1, current)] + result
使用它:
print [x[0] for x in compress(lst)]
明显而有效的方式是生成器:
def group_gen(lst):
buff = []
for item in lst:
if buff and item == buff[0]:
buff.append(item)
else:
if buff:
yield buff
buff = [item]
if buff:
yield buff
print list(map(len, group_gen(lst)))
使用以下方法检查:
print list(map(len, group_gen(lst)))