所以,如果我有这样的字典:
a = ['a':1, 'b':2, 'c':3]
显然,这三个数字的总和将是六。如何在任何此类列表中找到总和。我的意思是:
def compute_sum(a):
total = 0
for n in a:
total += prices[n]
return total
我是对的,这意味着我可以返回任何列表的总和吗?还有其他方法吗?你会如何使用相同或不同的功能?
答案 0 :(得分:2)
如果total
和prices[food]
属于同一类型,则该语句没有任何问题。但是,如果您尝试添加(或连接)不同类型,您肯定会遇到错误。
其次,您应该将shopping_list
作为参数传递给要迭代的函数,而不是food
。因此,应该更改函数接收的参数名称。
第三,total
变量应该在函数内部,而不是在外部。按照你写这个的方式,你会在执行时获得UnboundLocalError : local variable 'total' referenced before assignment
。函数有自己的局部范围,其中变量是单独定义的。
答案 1 :(得分:2)
你需要稍微改变你的循环
假设shopping_list类似于shopping_list = {'bread':1.00, 'eggs':0.99}
,那么你可以这样做:
def compute_bill(shopping_list):
total = 0.0
for food in shopping_list.keys():
total += shopping_list[food]
return total
答案 2 :(得分:2)
我不知道食物变量应该是什么意思!基于我对问题的理解,这里是代码:
def compute_bill(shopping_list, prices):
total = 0
for food in shopping_list:
total += prices[food]
return total
答案 3 :(得分:1)
sum(food_prices[food] for food in shopping_list)
如果你问我,应该可以正常工作
然而,这是你的方法已修复,所以它可以工作......
def compute_bill(): #no argument needed
total = 0 #initialize total to zero in your method
for food in shopping_list:
total += prices[food]
return total
答案 4 :(得分:0)
试试这个
def compute_bill(food):
for food,prices in shopping_list:
total += prices
return total
不知何故不能缩进
答案 5 :(得分:0)
我是怎么做到的:
shopping_list = []
prices = {"food_item": price_in_decimal, ... }
for item in stuff_you_want_to_buy:
shopping_list.append(item)
def compute_bill(shopping_list):
total = 0
for item in shopping_list:
try:
total += prices[item]
except KeyError as e:
# that item does not have a price, handle it
return total
更好(但更复杂):
class FoodItem(object):
def __init__(self, name, price):
"""Creates a new food object given its name and price as strings"""
import decimal
self.name = name
self.price = decimal.Decimal(price)
def __hash__(self):
return (self.name, self.price)
# This lets us use it as a dictionary key later
list_of_foods = [FoodItem("Apple","0.50"), FoodItem("Ham","6.50"), FoodItem("Milk","3.00"), ... ]
shopping_cart = list()
shopping_cart.append(list_of_foods[0])
shopping_cart.append(list_of_foods[0])
shopping_cart.append(list_of_foods[2])
# Two apples and a gallon of milk
def compute_bill(shopping_cart):
return sum([item.price for item in shopping_cart])
答案 6 :(得分:0)
我明白了。这是正确的代码:
def compute_bill(food):
total = 0
for n in food:
total += prices[n]
return total
事实证明,我应该把食物列为食物,而不是以食物作为参数制作不同的食物清单。感谢。