LIST INDICES ERROR 在 Python 2.7 中,请为代码中的选项 1 建议解决方案

LIST INDICES ERROR In Python 2.7, Please suggest solution for OPTION 1 in code

您好,我对使用字符串名称调用函数有疑问,因为它显示错误:LIST INDICES 必须是一个整数

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

请解释以下内容:

如何创建键名为空值的字典。 如何比较它是否是列表名称在函数的参数或字典键中给出。请建议代码。 我的代码的解决方案。对于选项 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)

预先感谢和干杯!

这意味着您传递的不是整数,而是列表索引。从它的外观来看,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'.

你需要检查传入的对象是一个字典(一个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

作为循环遍历食物时每次迭代的开始,在 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