0

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

ewr3243
  • 397
  • 3
  • 19
  • 1
    what's stopping you from simply iterating through the list and comparing? – rcshon Apr 17 '22 at 13:07
  • @rcshon execution time – ewr3243 Apr 17 '22 at 18:54
  • this is a simple linear-time operation just with the option of early stopping. Execution time shouldn't be a concern in cases like this unless you're doing something like HFT, which I doubt is the case since Python. – rcshon Apr 17 '22 at 19:20
  • A simple iteration with early stopping like @NYC Coder's answer works better if somehow execution time is really a concern, probably the fastest way to natively solve your problem without involving Cython. Since there is a conditional check, the iterator/generator approach requires going through the full list to check your condition before calling `next` only to return the first element, losing the benefit of early stopping, hence slower. – rcshon Apr 17 '22 at 19:21

4 Answers4

1

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))
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
0

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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

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.

AJH
  • 799
  • 1
  • 3
  • 16
0

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

ewr3243
  • 397
  • 3
  • 19