[英]Deleting an element from a list of tuples and then calculating a total price based on elements within each tuple
我试图解决一个家庭作业问题,该问题涉及根据元组列表处理订单,其中元组列表包含项目名称,数量和每项价格。
通过在删除项目后取列表中每个元组的第一和第二索引,然后对列表中剩余的每个元组的乘积求和,来计算总数。
我必须在process_order()函数中执行这些操作,但是当我尝试从列表中删除一个元组时,我仍然遇到问题,因为while循环一直在运行,并删除所有元素,始终使总数等于0 。
起始代码如下:
total = 0
def process_order(x_list):
x = [("oranges", 4, 3.22),("gummy bears",1,1.99),("sour bites", 3, 2.33), ("antacid", 1, 5.33)]
while(len(x)>0):
process_order(x)
print("total price: ", total)
这里是,
total = 0
x = [("oranges", 4, 3.22),
("gummy bears", 1, 1.99),
("sour bites", 3, 2.33),
("antacid", 1, 5.33)]
def process_order(x_list):
# calculate the cost of the first element and remove it
cost = x_list[0][1] * x_list[0][2]
del x_list[0]
return cost
while x:
total += process_order(x)
print(total)
# 27.19
我决定添加第二个答案,以回应BcK的回答:
另外,我不允许更改process_order()函数下面的任何代码。
从技术上讲这是可行的,但随后的问题对我来说有点奇怪。 为了使process_order
定义下方的代码能够正常工作而无需进行修改,您必须更改total
定义方式。 我觉得很奇怪,因为更改total
仅是由于以下事实,即它在技术上 超出了process_order
的定义,这对我来说似乎是一个很弱的借口。
total
的问题的症结在于直观的答案是:
def process_order(x_list):
{do stuff}
total += quantity * cost
该解决方案不起作用的原因是因为在范围内分配变量(在本示例中, total =
total +=
段)创建了一个引用,该引用取代了任何“较高”范围的引用。 这意味着不能在process_order
的范围内分配 total
(在当前限制下可以从技术上实现,但是需要一点黑客技术),或者必须引用位于外部范围内的total
变量才能进入内部范围。
实现后者的最简单方法是使用global关键字。 我确实非常不喜欢global
关键字( 并且有些人同意我的观点),但是由于任何原因它不断弹出,所以这里是您的用法(以及为您编写process_order
的另一种方法)学习乐趣)。
## Declare total as global variable
global total
## Set total
total = 0
def process_order(x_list):
""" Remove an an order item (as a tuple (name, quantity, cost) ) from x_list and add it to the global total"""
## Let the interpreter know that you plan on using total in this scope
global total
## List.pop is a good way to incrementally destroy a list
## (you can use an index as an argument: the default is -1)
item = x_list.pop()
## This takes advantage of sequence unpacking and multiple assignment
(name,quantity,price) = item
## You can now assign to total because it has been declared as a global variable
total += quantity * price
## The rest is unchanged
x = [("oranges", 4, 3.22),("gummy bears",1,1.99),("sour bites", 3, 2.33), ("antacid", 1, 5.33)]
while(len(x)>0):
process_order(x)
print("total price: ", total)
## Outputs: >> total price: 27.19
话虽这么说,我会更快地假设分配器中存在一些通信错误; 我认为,更改while
循环以匹配BcK的示例将更加有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.