【发布时间】:2021-12-31 09:32:23
【问题描述】:
所以我创建了一个列表和一个函数,它返回一个单独的列表作为字典,就像这样 所以第一个列表是这样的
r = ["T-bone", "Green Salad1"]
将输出作为字典返回的函数是这个......
def rdict(recipes):
recipes_splitted = {}
for r in recipes:
recipe_name, parts = r.split(":")
recipe_parts = {}
for part in parts.split(','):
product, number = part.split('*')
recipe_parts[product] = int(number)
recipes_splitted[recipe_name] = recipe_parts
return recipes_splitted
上述函数的输出在 dictionary 中,就像这样 btw
{'Pork Stew': {'Cabbage': 5, 'Carrot': 1, 'Fatty Pork': 10}, 'Green Salad1': {'Cabbage': 10, 'Carrot': 2, 'Pineapple': 5}, 'T-Bone': {'Carrot': 2, 'Steak Meat': 1}}
所以现在,我正在尝试创建一个函数extract(recipes, data),它将返回提供的字典中的值和列表提供的匹配键。返回类型应为列表。
例如,如果输入是
extract(recipes = ["T-bone", "Green Salad1"], data = {'Pork Stew': {'Cabbage': 5, 'Carrot': 1, 'Fatty Pork': 10}, 'Green Salad1': {'Cabbage': 10, 'Carrot': 2, 'Pineapple': 5}, 'T-Bone': {'Carrot': 2, 'Steak Meat': 1}} )
输出将返回以下列表
["Carrot:2, Steak Meat:1","Cabbage: 10, Carrot: 2, Pineapple: 5"]
我应该在 estract(recipes, data) 下写什么以获得正确的输出??
【问题讨论】:
-
你期望返回类型是什么?一个字典中不能有两次相同的键 (
Carrot)。 -
没有胡萝卜不是关键...在我的示例中,胡萝卜是 T 骨和绿色沙拉的一部分...我只想要一个返回 ["Carrot:2, Steak Meat: 1","Cabbage: 10, Carrot: 2, Pineapple: 5"] 当 Tbone 和 Green Salad1 被调用时