python: find value within range in float array

心不动则不痛 提交于 2019-12-20 05:38:19

问题


I have the following sorted python list, although multiple values can occur:

[0.0943200769115388, 0.17380131294164516, 0.4063245853719435, 
 0.45796523225774904, 0.5040225609708342, 0.5229351852840304, 
 0.6145136350368882, 0.6220712583558284, 0.7190096076050408, 
 0.8486436998476048, 0.8957381707345986, 0.9774325873910711, 
 0.9832076130275351, 0.985386554764682, 1.0]

Now, I want to know the index in the array where a particular value may fall:

For example, a value of 0.25 would fall in index 2 because it is between 0.173 and 0.40. I guess I can go through the list and do this in a for loop but I was wondering if there is some better way to do this which maybe more computationally efficient. I create this array once but have to perform many lookups.


回答1:


>>> vals = [0.0943200769115388, 0.17380131294164516, 0.4063245853719435, 
 0.45796523225774904, 0.5040225609708342, 0.5229351852840304, 
 0.6145136350368882, 0.6220712583558284, 0.7190096076050408, 
 0.8486436998476048, 0.8957381707345986, 0.9774325873910711, 
 0.9832076130275351, 0.985386554764682, 1.0]

>>> import bisect
>>> bisect.bisect(vals, 0.25)
2



回答2:


If you know the list is already sorted, then the textbook solution is to do a binary search. You keep two index bounds, min and max. Initialize them to 0 and len - 1. Then set mid to be (min + max) / 2. Compare the value at index mid with your target value. If it's less, then set min to mid + 1. If it's greater, then set max to mid - 1. Repeat until you either find the value or until max < min, in which case you will have found the desired index in O(log(n)) steps.



来源:https://stackoverflow.com/questions/33323892/python-find-value-within-range-in-float-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!