我有一个整数列表。然后我想改变这个列表,让它不包含,比如说一行四个1:s,而是说[[4, 1]]
。所以我做了一个函数,但是得到了一个意想不到的结果。你知道吗
这就是函数
compressed3 = []
def repeat_comp(data):
rep = 1
for i, item in enumerate(data):
if i < len(data) - 1:
if item == data[i + 1]:
rep += 1
else:
compressed3.append([rep, data[i - 1]])
rep = 1
else:
if item == data[i - 1]:
rep += 1
else:
compressed3.append([rep, data[i - 1]])
rep = 1
repeat_comp(compressed2)
这是compressed2
列表
[0,
1,
2,
3,
1,
1,
1,
1,
4]
下面是函数的结果与预期结果的比较
# output of function
[[1, 2832], # why this? (this number is one less than the lenght of another list that has nothing with this list to do)
[1, 0],
[1, 1],
[1, 2],
# excluded value here
[4, 1],
[1, 1], # why this?
[1, 4]]
# expected result
[[1, 0],
[1, 1],
[1, 2],
[1, 3],
[4, 1],
[1, 4]]
这很好地说明了为什么函数应该是idempotent,也就是说,对于相同的输入,函数的每次调用都应该产生相同的结果。通过将结果列表
compressed3
移到函数之外,调用者要确定哪些调用会改变这个全局变量;几乎不可避免地,会出现混淆的结果。你知道吗我将使用^{} 编写如下函数:
您只需更改代码中的两个内容即可获得预期的结果:
将
compressed3
列表移到函数中,让函数返回它,这样每次调用函数时compressed3
都会被清除。然后可以将返回的列表分配给另一个变量:我把
data[i - 1]
改成了item
print(result)
会给你[[1, 0], [1, 1], [1, 2], [1, 3], [4, 1], [1, 4]]
相关问题 更多 >
编程相关推荐