为什么指数超出范围? (蟒蛇)

时间:2016-11-30 22:42:10

标签: python

我运行下面的代码并引发一个错误,指出food_quant = item[1]列表索引超出范围。我检查确保item实际上是一个列表,并且两个项目也正确地添加到字典中。问题出在"Add"命令上。此外,这只是一个片段,因为程序的其余部分不相关,所以是的,我确实在此部分上面定义了适当的词典和列表。

    item = input("Please enter an item with its quantity separated by a hyphen (Ex. Apples-3) or any of the commands described above." )
    item = item.split('-')
    food_item = item[0]
    food_quant = item[1]
    foodquant_dict[food_item] = food_quant
    if item == "Add":
        for key in foodquant_dict:
            groceryfood_list.append(key)
        print (groceryfood_list)

1 个答案:

答案 0 :(得分:1)

如果任何输入中至少包含连字符的输入(例如"添加"或任何不包含连字符的任意输入),您的程序仍会尝试设置food_quant = item[1],如果输入没有至少一个连字符(即如果列表中没有任何内容可以拆分,则您的项目将是仅包含该项目的列表),这不存在。

举例说明要点:

>>> case1 = "item-2".split("-")
>>> case1
['item', '2']
>>> case2 = "item".split("-")
>>> case2
['item']

显然,为后一种情况调用case2[1]会导致IndexError,因为列表中只有一个元素。您需要验证输入是否包含破折号,或验证拆分列表是否包含多个元素。验证列表长度的示例:

item = input("enter your input\n")
item = item.split("-")
if len(item) > 1:
    a = item[1]
相关问题