我试着写一个小程序,根据特定的列表计算账单。其中一个需求是根据取出的内容更改为库存。我用下面的方式写了我的代码,至少从概念上讲,我觉得我有正确的想法。
shopping_list = ["banana", "orange", "apple"]
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] = stock[item] - 1
return total
else:
return "Sorry: Out of Stock"
return total
不幸的是,它不能工作。我已经找到了一个潜在的解决方案,并找到了一个类似这样的解决方案。
groceries = ["banana", "orange","apple"]
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def computeBill(food):
total = 0
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
return total
print computeBill(groceries)
我看到的主要区别在于这些代码:
stock[item] = stock[item] - 1
stock[item] -= 1
两者之间的主要区别是什么?为什么第二个可以工作?"-=“到底是做什么的?如果这是一种让同样的东西工作的不同方法,我可以理解,但它们并不等同,这让我感到困惑。任何意见都将非常感谢,并为我的无知/愚蠢提前道歉。
发布于 2016-07-08 04:35:44
对于数值变量,运算符-=
与分配比当前值小1的值完全相同。但这两个版本之间还有另一个区别:只要您检查购物清单中的一个元素,您的解决方案就会返回一个值。返回会终止函数,所以只在计算完成时才执行。
发布于 2016-07-08 04:37:02
问题可能是这样的:
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] = stock[item] - 1
return total
在这里,您在循环中间返回,因此它将只处理来自food
的一项。在第二个示例中,唯一的return语句位于循环的末尾。
发布于 2016-07-08 04:43:36
除了运行演示差异的程序之外,还有什么更好的方法来向您展示差异呢?试着运行下面的程序,并注意它打印到屏幕上的内容。
#! /usr/bin/env python3
def main():
stock = dict(apple=Number(100))
item = 'apple'
print('Memory location of stock[item]:', id(stock[item]))
stock[item] -= 1
print('Memory location of stock[item]:', id(stock[item]))
stock[item] = stock[item] - 1
print('Memory location of stock[item]:', id(stock[item]))
class Number:
__slots__ = '__value'
def __init__(self, value):
self.__value = value
def __repr__(self):
return repr(self.__value)
def __sub__(self, other):
type_of_self = type(self)
if isinstance(other, type_of_self):
other = other.__value
return type_of_self(self.__value - other)
def __isub__(self, other):
if isinstance(other, type(self)):
other = other.__value
self.__value -= other
return self
if __name__ == '__main__':
main()
第一个操作可以在适当的位置改变对象。第二个操作将创建一个新对象并替换旧对象。请注意,这回答了您的问题,但不能解决您的问题。
https://stackoverflow.com/questions/38254681
复制相似问题