-1

(Re-edited) For example, I have a list-like array:

l = [0.3, 2.3, 3.1, 4.5] # value can be any numeric type

Then given a number 1.2, as it is between 0.3 and 2.3, index 1 should be returned, and given a number 3.3, which is between 3.1 and 4.5, index 3 should be returned, for value less than 0.3, should return index 0, etc.

Basically for whatever input value, depends on the bin it falls into, return the index of that bin.

I hope not use if else statement, as the number of items in the list could be huge.

I guess the question should have been asked somewhere, but I just can't locate it.

(BTW, I actually remember there is a built-in function in numpy does the trick, but I can't recall anymore ...)

MJeremy
  • 1,102
  • 17
  • 27

3 Answers3

1
>>> l.index(round(1.2))
0
>>> l.index(round(3.3))
2

Assuming normal rounding rules.

Snorre Løvås
  • 251
  • 1
  • 5
0

The floor function from math library can also be used.

>>> l.index(floor(1.2))
0
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Other answers assumed that we have order step 1 array. in general form you can use something like this:

# for 1.5
l.index(max(x for x in l if x < 1.5))
# output: 0
# for 2.5
l.index(max(x for x in l if x < 2.5))
# output: 1

Caution: I assumed that there is no repeat in data and it sorted

wjandrea
  • 28,235
  • 9
  • 60
  • 81
SirSaleh
  • 1,452
  • 3
  • 23
  • 39