【发布时间】:2016-06-04 10:55:43
【问题描述】:
(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
我知道这很长,但是我不知道如何解决这个问题,而且我所谓的“老师”也不是很有帮助。
【问题讨论】:
-
这意味着您正在尝试访问不存在的列表索引
-
请提供minimal reproducible example,而不仅仅是代码转储。
-
我尝试运行您的代码并在第 1 行获得了
IndentationError: unexpected indent。请咨询Markdown help - Code and Preformatted Text 并重试。 -
欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布代码并准确描述问题之前,我们无法有效地帮助您。 @SirParselot 已经解释了基本信息。例如,如果您的列表中有 10 个元素,则您的合法下标为 0-9。如果您尝试获取元素 15,则会收到此错误。
-
@SirParselot 但是哪个?在我的文本文件中,有 5 个不同的冒号分隔符,每个都有信息,文本文件引用它。