【发布时间】:2020-04-07 08:36:21
【问题描述】:
我有一个整数列表。然后我想更改列表,以便它不包含,比如说连续四个 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]]
【问题讨论】:
标签: python python-3.x list function compression