TypeError: list indices must be integers, not float

╄→гoц情女王★ 提交于 2019-12-04 15:43:21

问题


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

def main():
    names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter',
             'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle',
             'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']

    entered = input('Enter the name of whom you would you like to search for:')
    binary_search(names, entered)

    if position == -1:
        print("Sorry the name entered is not part of the list.")
    else:
        print(entered, " is part of the list and is number ", position, " on the list.")
    input('Press<enter>')

def binary_search(names, entered):
    first = 0
    last = len(names) - 1
    position = -1
    found = False

    while not found and first <= last:
        middle = (first + last) / 2

        if names[middle] == entered:
            found = True
            position = middle
        elif names[middle] > entered:
            last = middle - 1
        else:
            first = middle + 1

    return position

main()

Error is:

TypeError: list indices must be integers, not float

I am having trouble understanding what this error message means.


回答1:


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.




回答2:


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.




回答3:


I can be wrong but this line:

binary_search(names, entered)

would not be

position = binary_search(names, entered)



回答4:


How to reproduce the above error simply:

>>> stuffi = []
>>> stuffi.append("foobar")
>>> print(stuffi[0])
foobar
>>> stuffi[0] = "failwhale"
>>> print(stuffi[0])
failwhale
>>> stuffi[0.99857] = "skipper"

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not float

If you're hitting stackoverflow because you got this error. It means you aren't reading or understanding the error message. The error message is perfect, it tells you exactly what is wrong and it tells you where you made the mistake as well.

Arrays are indexed by whole numbers, you are passing a non-whole number into it, and the interpreter tells you that you can't do that because it makes no sense.

The tutorials you need to revisit are:

"Python array tutorial"
"Python floats and primitive types tutorial"

Your variable needs to be cast to a whole number before it can be used to pick an array index.

Koan:

A man walks into a bar, and orders 1.1195385 beers, the bartender rolls his eyes and says: TypeError: beer orders must be whole integers, not fractions.



来源:https://stackoverflow.com/questions/13355816/typeerror-list-indices-must-be-integers-not-float

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