如何在列表中获取连续数字序列,如果它在X的范围内[重复]。

问题描述 投票:0回答:1
data = [1, 2, 5, 6, 7, 9, 22, 24, 26, 29] 
x=2

应该返回。

[[1, 2], [5, 6, 7, 9], [22, 24, 26], [29]]

我的代码。

from operator import itemgetter  
from itertools import groupby 
for k, g in groupby(enumerate(data), lambda x:x[1]-x[0]):
    res.append(list(map(itemgetter(1), g)))

该代码返回一个连续的1序列。

`([[1, 2], [5, 6, 7], [9], [22], [24], [26], [29]] )`  

如何修改这段代码以获得上述输出或其他方法。

python list algorithm data-structures
1个回答
2
投票

使用numpy来处理。

from numpy import diff, where, split
result= split(data, where(diff(data)>x)[0]+1 )
print(list(map(list, result)))

输出:

[[1, 2], [5, 6, 7, 9], [22, 24, 26], [29]]
© www.soinside.com 2019 - 2024. All rights reserved.