2012-11-13 80 views
13

我有一個產生錯誤的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 

我無法理解什麼這個錯誤信息的意思。

+1

請給予包含回溯的完整錯誤消息。 – BrenBarn

回答

25

它看起來像你使用Python 3.x. Python 3.x的一個重要區別是處理方式。當你做x/y時,Python 2.x中返回一個整數,因爲小數被截斷(floor division)。但是,在3.x中,/運算符執行「真」除法,導致產生float而不是整數(例如1/2 = 0.5)。這意味着你現在試圖使用float來引用列表中的一個位置(例如my_list[0.5]甚至my_list[1.0]),這不會像Python期待的整數一樣工作。因此,您可能首先要嘗試使用middle = (first + last) // 2,並進行調整,以便返回所期望的結果。 //表示Python 3.x中的地板部分。

+0

很好的答案 - 非常清楚。 – gahooa

+0

謝謝@gahooa :) – RocketDonkey

+0

太棒了!謝謝! :) – Francisunoxx

0

如何簡單地重現上述錯誤:如果你打的是計算器,因爲你得到這個錯誤

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

。這意味着你沒有閱讀或理解錯誤信息。錯誤信息是完美的,它告訴你到底什麼是錯誤的,它告訴你你犯了什麼錯誤。

數組通過整數進行索引,您將一個非整數傳入它,並且解釋器告訴您不能這樣做,因爲它沒有任何意義。

你需要重新審視教程:

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

你的變量需要轉換爲整數,然後才能將用於選擇一個數組索引。

公案:

一名男子走進酒吧,和訂單1.1195385啤酒,酒保翻了個白眼,說:TypeError: beer orders must be whole integers, not fractions.

0

我可能是錯的,但此行:

binary_search(names, entered) 

不會是

position = binary_search(names, entered) 
相關問題