0

I would like to group consecutive numbers from a list with a tolerance of 3 between elements of the list. Example : having a list like [242, 243, 244, 246, 2933, 2936, 2937, 2938] I want to have a result like [[242, 243, 244, 246],[2933, 2936, 2937, 2938]]

I am using this code but it gives me errors :

def groupEl(list1, tol): 
    res = [] 
    last = list1[0] 
    for ele in list1: 
        if ele-last <= tol: 
            yield res 
            res = [] 
        res.append(ele) 
        last = ele 
    yield res 

I get on terminal an error message like this : <generator object split_tol at 0x7f359d7f2550> Please help!

coder96
  • 63
  • 5
  • 1
    Thats not an error! :) The yield keyword returns a generator-object. If you want to see it as a list you can simply write: `return res` – Serial Lazer Nov 11 '20 at 11:01
  • thank you @SerialLazer even when I replace yield with return I still don't have what I want. I did some changes at the code and now it gives me only the first group of consecutive numbers, not all groups. The line I chenged is : `if ele - last > tol` – coder96 Nov 11 '20 at 11:16
  • Thats because the logic seems incorrect, trying debugging – Serial Lazer Nov 11 '20 at 11:18
  • You can use `yield`, just call the function as `list(groupEl(...))` – Tomerikoo Nov 11 '20 at 11:27
  • Does this answer your question? [Understanding generators in Python](https://stackoverflow.com/questions/1756096/understanding-generators-in-python) – Tomerikoo Nov 11 '20 at 11:32
  • Also see: https://stackoverflow.com/questions/24130745/convert-generator-object-to-list-for-debugging – Tomerikoo Nov 11 '20 at 11:32

1 Answers1

1

Your logic is exactly the opposite than what you want here ele-last <= tol. and even after this, you will only receive one list and not all.

This will help you:

def groupEl(list1, tol): 
    res = [] 
    temp=[]
    last = list1[0] 
    for ele in list1: 
        if abs(ele-last) > tol: 
            res.append(temp)
            temp=[]
        temp.append(ele) 
        last = ele 
    res.append(temp)
    return res 
Yash
  • 1,271
  • 1
  • 7
  • 9