json 如何使用对象中的值打印数组的名称?

x6492ojm  于 2023-02-26  发布在  其他
关注(0)|答案(3)|浏览(172)

我正在做我的第一个编码项目(交互式烹饪书),我遇到了一个障碍,我试图通过在终端输入成分名称(面粉)打印数组的名称(巧克力饼干),我使用python来做这个。这里是我的json文件代码的一个例子:

{
    "Recipes": [
        
     "chocolate chip cookie",[
        {
            "ingredients": "flour"
        },
        {
             "instructions": "Step 1: Preheat Oven to 375"  
        },
        {
            "category": "Cookies"
        }
         ]
    ]
}

下面是我python代码的摘录:

response = input("are you looking for recipes with ingredients on hand (if so please enter 'ingredients') or are you looking for something to cook/bake? (if so please enter 'Cook/Bake')\n")
if response == "ingredients":
    print("please enter ingredients")
    ingredients = input("enter ingredients separated by commas: ")
    ingredients = ingredients.split(",")
    for x in ingredients:
     import json 
     #pulling ingredients from cookbook.json(?)
     with open('cookbook.json', 'r') as f:
        data = json.load(f)
plicqrtu

plicqrtu1#

最好按如下方式组织数据

{
    "Recipes": [
        {   "name": "chocolate chip cookie",  
            "ingredients": [
                 "flour"
            ],
            "instructions": "Step 1: Preheat Oven to 375",  
            "category": "Cookies"
        }
         
    ]
}

最好将只需要执行一次的操作移到代码的顶部

这包括JSON的导入和阅读。

import json 
with open('cookbook.json', 'r') as f:
    cookbook = json.load(f)

response = input("are you looking for recipes with ingredients on hand (if so please enter 'ingredients') or are you looking for something to cook/bake? (if so please enter 'Cook/Bake')\n") 
if response == "ingredients":

    print("please enter ingredients")
    ingredients_comma_separated = input("enter ingredients separated by commas: ")
    ingredients = ingredients_comma_separated.split(",")

    print("Matches for ingredient list", ingredients,":")
    for recipe in cookbook["Recipes"]:
        if all([ingredient in recipe["ingredients"] for ingredient in ingredients]):
            print(recipe)

当你在测试程序时,问答模式会让你发疯

在开发过程中使用这种布局会更好。稍后您可以取消对问题的注解。

import json 
#pulling ingredients from cookbook.json(?)
with open('cookbook.json', 'r') as f:
    cookbook = json.load(f)

# response = input("are you looking for recipes with ingredients on hand (if so please enter 'ingredients') or are you looking for something to cook/bake? (if so please enter 'Cook/Bake')\n") 
# if response == "ingredients":
if True:

    # print("please enter ingredients")
    # ingredients_comma_separated = input("enter ingredients separated by commas: ")
    # ingredients = ingredients_comma_separated.split(",")

    available_ingredients = ["flour"]
    print("Matches for ingredient list", available_ingredients,":")
    for recipe in cookbook["Recipes"]:
        if all([ingredient in available_ingredients for ingredient in recipe["ingredients"]]):
            print(recipe)

    available_ingredients = ["flour","eggs"]
    print("Matches for ingredient list", available_ingredients,":")
    for recipe in cookbook["Recipes"]:
        if all([ingredient in available_ingredients for ingredient in recipe["ingredients"]]):
            print(recipe)

    available_ingredients = []
    print("Matches for ingredient list", available_ingredients,":")
    for recipe in cookbook["Recipes"]:
        if all([ingredient in available_ingredients for ingredient in recipe["ingredients"]]):
            print(recipe)
ru9i0ody

ru9i0ody2#

您的数据结构对于手头的用途来说相当笨拙。

  • “Recipies”应该是字典(对象)列表,而不是交替字符串和列表的列表
  • 菜谱的属性应该保存在一个字典中,而不是保存在一个键字典列表中
  • “配料”应该是一个清单(否则如果不把配料组合起来,就不算什么食谱)

根据您现有的数据,查找配方名称的过程(可能过于复杂)可能如下所示:

data  = {
    "Recipes": [
        
     "chocolate chip cookie",[
        {
            "ingredients": "flour"
        },
        {
             "instructions": "Step 1: Preheat Oven to 375"  
        },
        {
            "category": "Cookies"
        }
         ]
    ]
}

onHand = {"flour","chodolate"}

recipe = [ name for name,recipe in zip(*[iter(data["Recipes"])]*2)
                for fields in recipe for field,value in fields.items()
                if field=="ingredients" and value in onHand ]

['chocolate chip cookie']
7xllpg7q

7xllpg7q3#

首先,我建议将json文件的结构更改为,例如:

{"Recipes": [{
"name":"chocolate chip cookie", 
"ingredients": ["flour", "chocolate"], 
"instructions": ["Preheat Oven to 375", "Preheat Oven to 375 again??"], "category": "Cookies"
}]}

现在您有了一个名为配方的列表,该列表中的每个项目都是一个配方。
每个配方有4个变量:名称、成分、说明、类别。
这样你就可以循环每个食谱中的每一种成分,看看它们是否匹配。
如果你只想看到第一个结果,在is语句中放一个break

for x in ingredients:
   for recipe in data['Recipes']:
      if x in recipe['ingredients']:
         print(recipe)
         break

我还注意到你把import放在for循环里面,请不要这样做,把它放在文件的顶部,以确保它只被导入一次。
另外,不要在for循环中使用**with open()**语句,最好只使用一次,读取数据并将数据保存到变量中:

import json 

data = None

with open('cookbook.json', 'r') as f:
    data = json.load(f)

for x in ingredients:
    for recipe in data['Recipes']:
        if x in recipe['ingredients']:
            print(recipe['name])
            break

要回答您的第一个问题:

  • 按照我上面展示的方法,**print(recipe ['name])**将打印名称。

相关问题