2016-11-02 26 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