[英]How can I let python print out the right output using a dictionary?
所以我創建了一個列表和一個 function ,它返回一個單獨的列表作為字典,就像這樣,所以第一個列表是這個
r = ["T-bone", "Green Salad1"]
和返回 output 作為字典的 function 是這個......
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
上面 function 中的 output 在像這樣的字典中
{'Pork Stew': {'Cabbage': 5, 'Carrot': 1, 'Fatty Pork': 10}, 'Green Salad1': {'Cabbage': 10, 'Carrot': 2, 'Pineapple': 5}, 'T-Bone': {'Carrot': 2, 'Steak Meat': 1}}
所以現在,我正在嘗試創建一個 function 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}} )
output 將返回以下列表
["Carrot:2, Steak Meat:1","Cabbage: 10, Carrot: 2, Pineapple: 5"]
我應該在 estract(recipes, data) 下寫什么以獲得正確的 output?
嘗試:
def extract(recipes, data):
result = []
for r in recipes:
result.append(", ".join(f"{k}:{v}" for k, v in data[r].items()))
return result
結果:
['Carrot:2, Steak Meat:1', 'Cabbage:10, Carrot:2, Pineapple:5']
沒有join
、 items
和dict
理解:
def extract(recipes, data):
result = []
for r in recipes:
tmp = []
for key in data[r]:
tmp.append(f"{key}:{data[r][key]}")
final_string = ""
for i in range(len(tmp)):
if i < len(tmp) - 1:
final_string += tmp[i] + ", "
else:
final_string += tmp[i]
result.append(final_string)
return result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.