这是我遇到的一个教程问题,在学习Python大约一个月后,这对我很有挑战,因为我之前没有遇到过这类问题。
我想从2个词典中计算出给定“id”的总费用。
下面显示了我的词典:
a = {'HIN3': ('Plastic Wrap', 50), 'GIN2': ('Cocoa', 80), 'LIN1': ('Bayleaf', 25), 'TIN6': ('Powder Scent': 210), 'QIN8': ('Color 55': 75)}
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)])}
答案 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])
我没有测试这些,如果你发现问题,请告诉我。或者更好的是,自己修复它们:)毕竟,教程问题是供您探索的! 玩转,弄错,修复,再试一次。