“列表索引超出范围”?

时间:2016-02-22 20:41:16

标签: python list indexing

(PYTHON)。我一直收到错误,说“列表索引”是“超出范围”。这是什么意思?这是一段代码,它说错误是;

 products[L[0]] = {"desc" : L[1], "price" : L[2], "stock" : int(L[3]), "reorder" : int(L[4]), "target" : int(L[5])}

问题部分:

fi=open("data.txt", "r")  #Opens file in read mode
for line in fi: 
    L = line.rstrip().split(":")
    products[L[0]] = {"desc" : L[1], "price" : L[2], "stock" : int(L[3]), "reorder" : int(L[4]), "target" : int(L[5])}  #Reads file into a dictionary              
fi.close()  #Closes file

随附的文本文件(如果您尝试使用该代码,请确保将两者保存在同一文件夹中);

12345670:Burgers, £1:1.00:33:20:50  
34512340:Cheese, £2.50:2.50:11:15:30
98981236:Crisps, 0.55p:0.55:67:20:100
56756777:Spaghetti, £1.45:1.45:21:20:40
90673412:Sausages, £2.30:2.30:2:10:50
84734952:Lemonade, 0.99p:0.99:19:10:30
18979832:Ice Cream, £1.50:1.50:43:20:50
45353456:6 Pack of Beer, £5:5.00:16:10:30
98374500:Gum, 0.35p:0.35:79:10:90
85739011:Apples, 0.70p:0.70:34:20:50

我意识到这已经很久了但是我不知道如何解决这个问题而且我所谓的“老师”并没有很大帮助。

2 个答案:

答案 0 :(得分:2)

您可能已将products定义为list而非dict离合器。这会导致问题,因为您正在访问列表上的大型索引。

让我们看一下您的第一个数据行的示例(并填写分配行上的值):

12345670:Burgers, £1:1.00:33:20:50 

products[12345670] = {"desc" : "Burgers, £1", "price" : 1.00, "stock" : int(33), "reorder" : int(20), "target" : int(50)}

请注意,使用此方法,您将访问products 列表中的12345670th元素。这是一个很大的清单。如果这比您的列表大,那么您会得到IndexError表示索引超出范围。

但是,如果您要将products定义为字典(products = {}而不是products = []),这将起作用,因为它会将字典键12345670设置为等于该值上方。

答案 1 :(得分:0)

您最后一行的末尾可能有'\n',后面会添加另一个空白行。你需要忽略这种情况,这样才能做到这一点

with open("data.txt", "r") as fi:  #Opens file in read mode
    products={}

    for line in fi:
         line = line.strip('\n') #Removes any new lines
         if line: #Checks if line is not blank
             L = line.rstrip().split(":")
             print L
             products[L[0]] = {"desc" : L[1], "price" : L[2], "stock" : int(L[3]), "reorder" : int(L[4]), "target" : int(L[5])}  #Reads file into a dictionary 

['12345670', 'Burgers, \xa31', '1.00', '33', '20', '50']
['34512340', 'Cheese, \xa32.50', '2.50', '11', '15', '30']
['98981236', 'Crisps, 0.55p', '0.55', '67', '20', '100']
['56756777', 'Spaghetti, \xa31.45', '1.45', '21', '20', '40']
['90673412', 'Sausages, \xa32.30', '2.30', '2', '10', '50']
['84734952', 'Lemonade, 0.99p', '0.99', '19', '10', '30']
['18979832', 'Ice Cream, \xa31.50', '1.50', '43', '20', '50']
['45353456', '6 Pack of Beer, \xa35', '5.00', '16', '10', '30']
['98374500', 'Gum, 0.35p', '0.35', '79', '10', '90']
['85739011', 'Apples, 0.70p', '0.70', '34', '20', '50']