TypeError:list indices必须是整数,而不是float

时间:2012-11-13 04:59:07

标签: list python-3.x binary-search typeerror

我有一个产生错误的python 3.x程序:

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()

错误是:

TypeError: list indices must be integers, not float

我无法理解此错误消息的含义。

5 个答案:

答案 0 :(得分:41)

看起来你正在使用Python 3.x. Python 3.x的一个重要区别是处理除法的方式。执行x / y时,Python 2.x中返回一个整数,因为十进制被截断(楼层划分)。但是在3.x中,/运算符执行'true'除法,得到float而不是整数(例如1 / 2 = 0.5)。这意味着您现在正在尝试使用浮点引用列表中的位置(例如my_list[0.5]或甚至my_list[1.0]),这不会起作用,因为Python期望一个整数。因此,您可能首先要尝试使用middle = (first + last) // 2进行调整,以便结果返回您期望的结果。 //表示Python 3.x中的地板划分。

答案 1 :(得分:1)

在函数testOnData()上使用ANN和PyBrain时遇到了这个问题。

所以,我解决了这个问题,将“ //”而不是“ /”放在backprop.py源代码的索引中。

我更改了:

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

收件人:

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

希望它能对您有所帮助。

答案 2 :(得分:0)

我错了,但这一行:

binary_search(names, entered)

不会

position = binary_search(names, entered)

答案 3 :(得分:0)

Kinda参加聚会较晚,但您也可以使用:

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

在任何情况下,RocketDonkey答案都可以完美地解释为什么会出错。

为使代码正常工作,还应设置:

position = binary_search(names, entered)

如雨果·费雷拉(Hugo Ferreira)所述。

还要检查以下问题:What is the difference between '/' and '//' when used for division?

答案 4 :(得分:-1)

如何简单地重现上述错误:

>>> 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

如果您因为出现此错误而进入stackoverflow。这意味着您无法阅读或理解错误消息。错误信息是完美的,它会告诉您确切的错误,并告诉您错误的位置。

数组按整数编号,你将一个非整数传递给它,解释器告诉你你不能这样做,因为它没有任何意义。

您需要重新访问的教程是:

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

在将变量用于选择数组索引之前,需要将其转换为整数。

<强>公案:

一名男子走进一家酒吧,点了1.1195385颗啤酒,酒保翻白眼说:TypeError: beer orders must be whole integers, not fractions.