3 回答
TA贡献1833条经验 获得超4个赞
用 more_itertools.consecutive_groups
import more_itertools as mit
my_list = [1,2,3,4,5,9,10,11,12,13,14,15]
x = [list(group) for group in mit.consecutive_groups(my_list)]
oputput = []
for i in x:
temp = [i[0],i[1],i[-2],i[-1]]
output.extend(temp)
输出:
[1,2,4,5,9,10,14,15]
TA贡献1811条经验 获得超4个赞
您可以通过将列表与自身的偏移量为 1 进行压缩来配对相邻的列表项,但使用非连续值填充移位的列表,以便您可以遍历配对并确定存在一个单独的组一对不是 1:
def consecutive_groups(l):
o = []
for a, b in zip([l[0] - 2] + l, l):
if b - a != 1:
o.append([])
o[-1].append(b)
return [s[:2] + s[-2:] for s in o]
给定您的样本输入,consecutive_groups(my_list)返回:
[[1, 2, 4, 5], [9, 10, 13, 14], [20, 21, 26, 27]]
TA贡献1842条经验 获得超21个赞
仅使用标准itertools模块,您可以执行以下操作:
from itertools import count, groupby
def remove_middle_of_seq(lst):
out = []
index = count()
for _, sequence in groupby(lst, lambda value: value - next(index)):
seq = list(sequence)
out.extend([seq[0], seq[1], seq[-2], seq[-1]])
return out
my_list = [1,2,3,4,5, 9,10,11,12,13,14, 20,21,22,23,24,25,26,27]
print(remove_middle_of_seq(my_list))
# [1, 2, 4, 5, 9, 10, 13, 14, 20, 21, 26, 27]
在连续值的组中,值与其索引之间的差异是恒定的,因此groupby可以使用此差异作为关键字对它们进行分组。
添加回答
举报