0

I have various heights (z) that I want to classify into different layers. Looking online it looks like the bisect_left function is a good way of finding where in a list a value should appear. I have defined the name of each layer to be the position of a given z value in the list. For example, z=15.75 would correspond to layer 1. I have written the function below to implement this.

def layer_update(particle):

layers = [20,15.75,14.75,10.5,9.5,5.25,4.25]
z = particle["z"]

if z in layers:
    particle["layer"] = bisect.bisect_left(layers,z) 

else:
    particle["layer"] = bisect.bisect_left(layers,z) - 1

return(particle)

An if statement is included because my values of z will generally be the values included in the layers list. However, when I run the line

layers = [20,15.75,14.75,10.5,9.5,5.25,4.25]
bisect.bisect_left(layers,20)

I expect to get 0, but I get 7. I've read the documentation for the bisect function and can't see why this might be the case. Can anybody help?

Ps. I believe it might be because the layers list is in descending order, it's important for other parts of my code that this be the case, so ideally any solutions will maintain the list as is.

Eli Rees
  • 178
  • 2
  • 14
  • 2
    Everything in the `bisect` module is based on the assumption that the list is sorted in ascending order. It's written entirely in Python, so you could copy it and reverse all the comparison operators to get something that works the way you want. – jasonharper Mar 04 '20 at 18:05
  • @jasonharper That makes sense thank you. I'm still quite early in my python education so that might be a little challenging, is there a way to classify these values using the bisect output anyway? Or perhaps a different library function entirely? – Eli Rees Mar 04 '20 at 18:11
  • See related [How to use bisect.insort_left with a key?](https://stackoverflow.com/questions/27672494/how-to-use-bisect-insort-left-with-a-key) — possible duplicate. – martineau Mar 04 '20 at 18:41

0 Answers0