christylynn002 christylynn002 - 1 year ago 90
Python Question

Find index of first occurrence in sorted list

I have a sorted list that looks like this:

sortedlist = ['0','0','0','1','1,'1,'2',2','3']

I also have a count variable:

count = '1'

*note: sometimes count can be an integar greater that the max value in the list. For example
count = '4'

What I want to do is to find the first occurrence of the count in the list and print the index. If the value is greater than the max value in the list, then assign a string. Here is what I have tried:

maxvalue = max(sortedlist)
for i in sortedlist:
if int(count) < int(sortedlist[int(i)]):
indexval = i
if int(count) > int(maxvalue):
indexval = "over"

I thought the break would end the for loop, but I'm only getting results from the last if statement. Am I doing something incorrectly?

Answer Source

Your logic is wrong, you have a so called sorted list of strings which unless you compared as integer would not be sorted correctly, you should use integers from the get-go and bisect_left to find index:

from bisect import bisect_left

sortedlist = sorted(map(int, ['0', '0', '0', '1', '1', '1', '2', '2', '3']))

count = 0

def get_val(lst, cn):
    if lst[-1] < cn:
        return "whatever"
    return bisect_left(lst, cn, hi=len(lst) - 1)

If the value falls between two as per your requirement, you will get the first index of the higher value, if you get an exact match you will get that index:

In [13]: lst = [0,0,2,2]

In [14]: get_val(lst, 1)
Out[14]: 2

In [15]: lst = [0,0,1,1,2,2,2,3]

In [16]: get_val(lst, 2)
Out[16]: 4

In [17]: get_val(lst, 9)
Out[17]: 'whatever'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download