2016-11-30 117 views
-1

我運行下面的代碼,並提出一個錯誤,說food_quant = item[1]列表索引超出範圍。我檢查確認item實際上是一個列表,並且兩個項目都正確添加到字典中。問題在於"Add"命令。此外,這只是一個片段,因爲程序的其餘部分是不相關的,所以是的,我確實有這部分上面定義的適當的詞典和列表。爲什麼索引超出範圍? (Python)

item = input("Please enter an item with its quantity separated by a hyphen (Ex. Apples-3) or any of the commands described above.") 
    item = item.split('-') 
    food_item = item[0] 
    food_quant = item[1] 
    foodquant_dict[food_item] = food_quant 
    if item == "Add": 
     for key in foodquant_dict: 
      groceryfood_list.append(key) 
     print (groceryfood_list) 
+3

如果用戶輸入'Add',那麼'item = item.split(' - ')'後面會有多少元素? – user2357112

+0

您所描述的錯誤行不會出現在您引用的代碼中的任何位置 - 您的意思是'food_quant = item [1]'? –

+0

@ user2357112它應該有2個元素,比如'['Apple','3']' – tmp657

回答

1

如果不包含至少在連字符的任何輸入是給你的程序(例如,「添加」,或不包含連字符的任意輸入真),您progrma仍將嘗試置food_quant = item[1],不存在如果輸入沒有至少一個連字符(例如,如果在列表中沒有任何東西需要分割,那麼您的項目將是包含該項目的列表)。

一個例子來說明這一點:

>>> case1 = "item-2".split("-") 
>>> case1 
['item', '2'] 
>>> case2 = "item".split("-") 
>>> case2 
['item'] 

顯然,主叫case2[1]爲後者的情況下會導致IndexError,因爲在列表中僅一個元件。您需要驗證您的輸入是否包含短劃線,或者驗證分割列表是否包含多個元素。一個驗證列表長度的例子:

item = input("enter your input\n") 
item = item.split("-") 
if len(item) > 1: 
    a = item[1] 
+0

我想你的意思是'item = item.split(「 - 」)'或者'item = input(...)。split(「 - 」)' – Copperfield