Search code examples
pythoniteratorenumerate

Negative values in a certain range


Given a list:

a = [-20,-15,-10,-5,0]

and another:

b = [-3,-10,-14,-19,-13,-5,-0.5]

I now want a result dictionary that looks like the following:

N = {'-20 to -15': [-19], '-15 to -10': [-14,-13,-10], '-10 to -5': [-3,-5], '-5 to 0': [-0.5]} 

The problem now is that I already can't get the "range" check correct. Can someone help me with the error in the code? I tried to get the index via a while loop:

j=0
while j < len(a):
   index1 = next(x[0] for x in enumerate(b) if x[1] >= a[j])          
   index2 = next(x[0] for x in enumerate(b) if x[1] < a[j+1])
   j=+1

There seems to be a problem somehow with comparing the negative values, at least I think. I would be very grateful for help!


Solution

  • A list comprehension inside a dictionary comprehension should do it:

    >>> {f"{i} to {j}": [x for x in b if i < x <= j] for i, j in list(zip(a, a[1:]))}
    {'-20 to -15': [-19], '-15 to -10': [-10, -14, -13], '-10 to -5': [-10, -5], '-5 to 0': [-3, -5, -0.5]}
    

    Explanation:

    • list(zip(a, a[1:])): generates the ranges as a list of tuples
    • [x for x in b if i <= x <= j]: generates a list of values inside a given range
    • f"{i} to {j}": Formats the dictionary key