列表指数错误在Python 2.7中,请在代码中为OPTION 1建议解决方案

时间:2015-01-21 20:19:04

标签: python python-2.7 dictionary indices

您好我在使用字符串名称调用函数时有疑问,因为它显示错误:列表指示必须是整数

我同意错误陈述,但不知道该怎么做。当我将函数参数参数作为字典(选项2)给出时,其功能是接受它并顺利运行代码。 但是只给它一个密钥的名称(就像我在选项1中所做的那样),它显示了Indices错误,因为我正在访问key,这是一个字符串而不是整数&它没有带有值的键(这是不可用键的错误)。 所以,

请解释我:

如何创建具有键名但空值的字典。 如何比较它是否是列表名称在函数的参数或字典键中给出。请建议代码。 解决我的代码。对于选项1

代码:

 # CODE FOR DETRMINING PRICE AS PER STOCK
#PYTHON 2.7 SCRIPT 
stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

def compute_bill(food):
    x = 0
    total1 = 0
    total2 = 0
    z=0

    for key in food: # I KNOW I AM DOING ERROR HERE, BUT NO CLUE WHAT TO DO!!

        count = stock[key] #INTIAL COUNT
        print "this is the stock of %s : %d " % (key,count)

        count = stock[key] - food[key] # STOCK REMAINING
        print "this is the stock remaining of %s : %d " % (key,count)

        if count > 0: # CHECKING WHETHER IT IS IN STOCK OR NOT
            z = prices[key] * food[key] # FINDING TOTAL
            total1 = z + total1 # ACCUMLATING TOTAL
            print "this is the total1 of %s : %f \n" % (key,z)

        elif count <= 0: # OVER-STOCK OR EMPTY STOCK
            z = prices[key] * stock[key]
            total2 = z + total2
            print "this is the total2 of %s : %f \n" % (key,z)

        x = total1 + total2 #COMPUTING WHOLE TOTAL



    print "\n this is the whole total : %f \n" % x

    return x



 # JST WANT ALL PEAR
compute_bill(['pear']) #OPTION 1: NOT WORKING!! NEED SOLUTION

#OPTION 2 : WORKING : 
order = {'apple' : 1, 'banana' : 3, 'pear' : 3, 'orange' : 3}
    compute_bill(order)

提前谢谢&amp;干杯!!

3 个答案:

答案 0 :(得分:0)

这意味着您传递的不是整数作为列表索引。从它的外观来看,compute_bill()在列表中使用名为'pear'的字符串进行调用。然后该列表作为参数food传递。然后for语句将'pear'字符串作为键,如果将其应用于字典stock,则该字符串是正确的。但是,food仍然是一个列表,因此调用food['pear']会出错。它应该是food[0]。你可以用这个代替循环:

    for i in range(len(food)):
        key = food[i]

之后,您可以分别使用索引i和密钥key访问列表和字典。在这种情况下,food[0]不会产生整数值,但会使用字符串'pear'

答案 1 :(得分:0)

您需要检查传入的对象是字典(order)还是列表(item)...您还需要在第二个确切地确定您想要的行为但是,我想您想要回答可用库存的总价格:

def compute_bill(food):
    if isinstance(food, dict):
        compute_bill_for_order(food)
    if isinstance(food, list):
        compute_bill_for_items(food)

def compute_bill_for_order(order):
    for key in order.keys():  ## You also have to call the `keys` method
      # Here goes the exact same code you have for the cases
      # count > 0 and count <= 0
      # Basically, the `compute_bill` method
      pass

def compute_bill_for_items(items):
    total = 0
    for item in items:
        total += prices[item] * stock[item]
    return total

答案 2 :(得分:0)

作为循环食物的每次迭代的开始,在compute_bill函数中,我会提取所需食物的数量:

try:
  quantity = food[key]  # get only how much was asked
except TypeError:
  quantity = stock[key] # get all remaining food from the stock !

然后,只要您使用food[key],请使用新变量quantity