2016-11-02 38 views
1

我看了這個問題上的其他堆棧溢出帖子,但我仍然不明白這個程序我試圖做的錯誤。我不明白爲什麼List索引超出for循環中的if語句的範圍。請有人解釋給我,以及要改變什麼來解決它。列表索引超出範圍if語句

order = ["12345678", "2", "12345670", "2", "11111111", "3", "87654321", "8"] 
orderCount = 0 
productCount = 0 

file = open("file.txt", "r") 

print(len(order)) 

while orderCount < len(order): 
    for line in file: 
     product = line.split(",") 
     print(orderCount) 
     if order[orderCount] == product[0]: 
      totalCost = float(order[1]) * float(product[2].strip('\n')) 
      receipt = product[productCount], product[1], order[1], product[2].strip('\n'), str(totalCost) 
      receipt = " ".join(receipt) 
      print(receipt) 

     else: 
      print("Product not found.") 
     orderCount += 2 
+3

'orderCount'大於'order'的最大索引。你試圖用while循環來阻止它,但問自己:循環檢查'orderCount'的大小是多少,'orderCount'的大小是多少 –

回答

3

您在while循環中檢查orderCount,但在for循環中增加它。

您可以刪除while循環,並把這個裏面的for循環:

if len(order) <= orderCount: 
    break 
0

你不檢查,以確保orderCount小於len(order)你的內循環迭代;具有4行或更多行的文件將導致orderCount以8或以上結束,這對於order列表而言是超出範圍的。

一個簡單的方法來解決這個問題(雖然你將不得不評估自己是否會給你想要的行爲,我不能說這個),當orderCount >= len(order),如下所示是打破內循環:

while orderCount < len(order): 
    for line in file: 
     ... 
     orderCount += 2 
     if orderCount >= len(order): 
      break