📜  Python|对具有公差的连续列表元素进行分组

📅  最后修改于: 2022-05-13 01:55:33.312000             🧑  作者: Mango

Python|对具有公差的连续列表元素进行分组

有时,我们可能需要根据列表中的连续元素对列表进行分组。但一个有用的变体也可能是我们需要考虑容差水平的情况,即允许数字之间的跳跃值并且不完全连续,但允许数字之间的“间隙”。让我们讨论一种可以执行此任务的方法。

方法:使用生成器
执行此任务的粗暴方法。使用循环和生成器,可以执行此任务。切片由产量运算符负责,因此这个问题也可以通过对容差的小检查来解决。

# Python3 code to demonstrate working of
# Group consecutive list elements with tolerance
# Using generator
  
# helper generator
def split_tol(test_list, tol):
    res = []
    last = test_list[0]
    for ele in test_list:
        if ele-last > tol:
            yield res
            res = []
        res.append(ele)
        last = ele
    yield res
  
# initializing list
test_list = [1, 2, 4, 5, 9, 11, 13, 24, 25, 26, 28]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Group consecutive list elements with tolerance
# Using generator
res = list(split_tol(test_list, 2))
  
# printing result 
print("The splitted list is : " + str(res))
输出 :
The original list is : [1, 2, 4, 5, 9, 11, 13, 24, 25, 26, 28]
The splitted list is : [[1, 2, 4, 5], [9, 11, 13], [24, 25, 26, 28]]