TypeError: list indices must be integers, not float

前端 未结 4 594
感情败类
感情败类 2021-02-05 02:47

I have a python 3.x program that is producing an error:

def main():
    names = [\'Ava Fischer\', \'Bob White\', \'Chris Rich\', \'Danielle Porter\',
                    


        
相关标签:
4条回答
  • 2021-02-05 03:36

    I can be wrong but this line:

    binary_search(names, entered)
    

    would not be

    position = binary_search(names, entered)
    
    0 讨论(0)
  • 2021-02-05 03:37

    I had this problem when using ANN and PyBrain on function testOnData().

    So, I solved this problem putting "//" instead "/" inside the index on backprop.py source code.

    I changed:

    print(('Max error:', 
        max(ponderatedErrors), 
        'Median error:',
         sorted(ponderatedErrors)[len(errors) / 2])) # <-- Error area 
    

    To:

    print(('Max error:', 
        max(ponderatedErrors), 
        'Median error:',
         sorted(ponderatedErrors)[len(errors) // 2])) # <-- SOLVED. Truncated
    

    I hope it will help you.

    0 讨论(0)
  • 2021-02-05 03:40

    It looks like you are using Python 3.x. One of the important differences in Python 3.x is the way division is handled. When you do x / y, an integer is returned in Python 2.x because the decimal is truncated (floor division). However in 3.x, the / operator performs 'true' division, resulting in a float instead of an integer (e.g. 1 / 2 = 0.5). What this means is that your are now trying to use a float to reference a position in a list (e.g. my_list[0.5] or even my_list[1.0]), which will not work as Python is expecting an integer. Therefore you may first want to try using middle = (first + last) // 2, adjusting so that the result returns what you expect. The // indicates floor division in Python 3.x.

    0 讨论(0)
  • 2021-02-05 03:42

    Kinda late to the party but you could also use:

    middle = int((first + last) / 2)

    In any case why you are getting your error is perfectly explained in RocketDonkey answer.

    For your code to work you should also set:

    position = binary_search(names, entered)
    

    as Hugo Ferreira mentioned.

    Also check this question: What is the difference between '/' and '//' when used for division?

    0 讨论(0)
提交回复
热议问题