Home > other >  Finding index of nested list greater than a value
Finding index of nested list greater than a value

Time:04-18

I have a nested list

l1 = [ [0.1*x, 0.5*x] for x in range(6) ]

which gives

[[0.0, 0.0], [0.1, 0.5], [0.2, 1.0], [0.3, 1.5], [0.4, 2.0], [0.5, 2.5]]

Let's say val=0.35 is a variable. I am trying to find smallest index x such that of l1[x][0]>val, which is 4 in this case.

I want to use the iterator approach given here: https://stackoverflow.com/a/2236935/11638153

CodePudding user response:

Here's another way of doing using a method:

def get_smallest_index(list1):
    for i, l in enumerate(list1):
        if l[0] > val:
            return i
    return 0


if __name__ == '__main__':
    l1 = [[0.1*x, 0.5*x] for x in range(6)]
    val = 0.35
    print(get_smallest_index(l1))

CodePudding user response:

You can use the min - function together with enumerate with a comprehension to achive that:

values = [[0.0, 0.0], [0.1, 0.5], [0.2, 1.0], [0.3, 1.5], [0.4, 2.0], [0.5, 2.5]]

k = 0.35
idx = min( i for i,v in enumerate(values) if v[0] > k)

print(idx)

gives you

4

This will be suboptimal though, it is kindof better to use a normal loop with enumerate and break from it because this code has to iterate all elements, the loop can finish as soon as the first value is found.

CodePudding user response:

If you're willing to convert to a NumPy array, you could do:

l1 = np.array(l1)
val = 0.35

try:
  idx = np.where(l1[:, 0] > val)[0][0]
except:
  idx = None

The try, except block is just to catch the case where no idx in l1 meets the requirements.

CodePudding user response:

I solved the problem using next(x[0] for x in enumerate(l11) if x[1][0] > val )

  • Related