Search code examples
pythonlistdictionarynumberslist-comprehension

how to get original numbers from a list after computing the difference between to consecutive numbers


{0: [41, 42, 183, 186, 471, 493, 639, 642, 732, 734], 1: [477, 489, 490]}

consider I have a dictionary with a list as values.

I want to find the difference between two consecutive numbers in the list and if their difference is less than, say 40, I want to fetch the second consecutive number of those two numbers taken into consideration and store all such kinds of numbers in a list.

Can anyone please help me with this.


Solution

  • One way to approach this:

    data = {0: [41, 42, 183, 186, 471, 493, 639, 642, 732, 734], 1: [477, 489, 490]}
    x = 40
    
    {k: [b for a, b in zip(v, v[1:]) if a + x > b] for k, v in data.items()}
    # {0: [42, 186, 493, 642, 734], 1: [489, 490]}
    

    Or for a flat list:

    [b for v in data.values() for a, b in zip(v, v[1:]) if a + 40 > b]
    # [42, 186, 493, 642, 734, 489, 490]