如果州政府的列表索引超出范围

2024-06-26 14:51:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我查看了关于这个问题的其他堆栈溢出帖子,但是我仍然不理解我试图生成的这个程序的错误。我不明白为什么for循环中的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

Tags: forlenif堆栈lineorderproductfloat
2条回答

您没有检查以确保在内部循环的迭代中orderCount小于len(order);一个包含4行或更多行的文件将导致orderCount在8或8以上结束,这超出了order列表的界限。

解决这个问题的一个简单方法(尽管你必须评估一下自己,这是否会给你想要的行为,我不能这么说)是当orderCount >= len(order)这样的时候,从内部循环中跳出:

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

在while循环中检查orderCount,但在for循环中增加它。

您可以移除while循环并将其放入for循环中:

if len(order) <= orderCount:
    break

相关问题 更多 >