当两个相邻值差大于阈值时,如何将排序列表拆分为子列表

Dra*_*rys 6 python

输入:

  • a sorted list,像这样:[1,2,3,8,10,15,16,17,18,22,23,27,30,31]
  • 一个门槛,像这样: max_diff = 2

预期产量:

  • 子列表列表; 每个子列表包含相邻差异小于max_diff的值,如下所示:[[1, 2, 3], [8, 10], [15, 16, 17, 18], [22, 23], [27], [30, 31]]

这是我如何做到这一点,我想知道是否有更好的方法来做到这一点.

test_list = [1,2,3,8,10,15,16,17,18,22,23,27,30,31]
max_diff = 2

splited_list = []
temp_list = [test_list[0]]
for i in xrange(1,len(test_list)):
    if test_list[i] - temp_list[-1] > max_diff:
        splited_list.append(temp_list)
        temp_list = [test_list[i]]
    else:
        temp_list.append(test_list[i])        
    if i == len(test_list) -1:
        splited_list.append(temp_list)

print splited_list 
Run Code Online (Sandbox Code Playgroud)

Kas*_*mvd 2

您可以在列表理解中使用enumeratezip函数来查找值差异大于 2 的元素的索引,然后根据索引 list 拆分列表:

>>> li =[1, 2, 3, 8, 10, 15, 16, 17, 18, 22, 23, 27, 30, 31]
>>> inds=[0]+[ind for ind,(i,j) in enumerate(zip(li,li[1:]),1) if j-i>2]+[len(li)+1]
>>> [li[i:j] for i,j in zip(inds,inds[1:])]
[[1, 2, 3], [8, 10], [15, 16, 17, 18], [22, 23], [27], [30, 31]]
Run Code Online (Sandbox Code Playgroud)