Python问题:一个从两个给定字典计算值的函数

时间:2011-04-04 11:37:34

标签: python list dictionary sum

这是我遇到的一个教程问题,在学习Python大约一个月后,这对我很有挑战,因为我之前没有遇到过这类问题。

我想从2个词典中计算出给定“id”的总费用。
下面显示了我的词典:

a = {'HIN3': ('Plastic Wrap', 50), 'GIN2': ('Cocoa', 80), 'LIN1': ('Bayleaf', 25), 'TIN6': ('Powder Scent': 210), 'QIN8': ('Color 55': 75)}

第一个值是id,然后第二个包含对列表,包括名称和成本。

b = {'candy1': ('Choco fudge', [('HIN3', 1), ('GIN2', 5)]), 'candy2': ('Mint Lolly', [('LIN1', 3), ('GIN2', 1), ('HIN3', 1)]), 'candy3': ('MILK', [('HIN3', 1), ('TIN6', 4), ('QIN8', 1)])}

其中第一个值是dict b的id,第二个值是一个列表,其中包含生产产品所需的名称和成分。

现在我需要创建一个函数(get_cost(id)),它将给出给定dict b的id的总成本。
例如,get_cost('candy1')的结果将是450,因为它需要1 HIN3(50)和GIN2中的5(5 * 80 = 400)因此成本为50 + 400 = 450.请注意,我想将成本作为整数返回。

1 个答案:

答案 0 :(得分:2)

首先,一个易于理解的功能:

def getCost(id):
    total_cost = 0
    ingredients = b[id][1] # Second element of tuple is ingredient list

    for ingredient, amount in ingredients:
        total_cost += a[ingredient][1] * amount

    return total_cost

现在,一个可爱的单行:

def getCost(id):
    return sum(a[ingredient][1] * amount for ingredient, amount in b[id][1])

我没有测试这些,如果你发现问题,请告诉我。或者更好的是,自己修复它们:)毕竟,教程问题是供您探索的! 玩转,弄错,修复,再试一次