Python - 字典未正确更新

时间:2015-03-22 22:36:44

标签: python list dictionary

我正在尝试运行超市的这个程序。 但是,项目列表未正确更新。

stock = {
    "banana": 6,"apple": 0,"orange": 32,"pear": 15
}    
prices = {
    "banana": 4,"apple": 2,"orange": 1.5,"pear": 3
}

def compute_bill(food):
    total = 0
    for item in food:
        if stock[item] > 0:
            total += prices[item]
            stock[item] -= 1
    return total

print "\n"
print "     Welcome to Supermarket!"
print "List of grocery items :"
print("{:<5}{:<8}{:<9}{:<10}".format("Num","Item","  Cost","  In Stock"))
counter = 0
for x,y in enumerate(prices.items()):
    print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
    counter += 1

print "Specify the number of items : "
number = int (raw_input ())
order = {}
for i in range(number):
    groceryitem = raw_input("Please enter the name of product %s:" % (i+1))
    itemNo = int(raw_input("How many iteam %s ?" % groceryitem))
    order[groceryitem] = itemNo

total = compute_bill(order)
print "total",total

counter = 0
for x,y in enumerate(prices.items()):
    print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
    counter += 1

这低于我的输入和我得到的输出

                Welcome to Supermarket!
List of grocery items :
Num  Item      Cost     In Stock
1    orange    RS 1.50   32
2    pear      RS 3.00   15
3    banana    RS 4.00    6
4    apple     RS 2.00    0
Specify the number of items :
2
Please enter the name of product 1:banana
How many iteam banana ?4
Please enter the name of product 2:pear
How many iteam pear ?5

Num  Item      Cost     In Stock
1    orange    RS 1.50   32
2    pear      RS 3.00   14
3    banana    RS 4.00    5
4    apple     RS 2.00    0

因为我已经指定了4个香蕉和5个梨,所以没有任何物品应该从库存清单中减去。 为什么库存词典中的值没有得到更新。

请帮忙!

1 个答案:

答案 0 :(得分:1)

它们正在更新,但由于您编写了stock[item] -= 1,它们只减少了一个。如果您想根据购买的商品数量减少库存,则需要将其更改为stock[item] -= food[item]。您可能还需要执行total += food[item]*prices[item],以便“购物者”对所购商品的数量收取正确的费用。