json 条件随机选择

fiei3ece  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(133)

因此,我有一个JSON文件,其中填充了食谱,一个来自文件的示例:

{
      "id": 6,
      "name": "Lobster roll",
      "type": "fish",
      "ingredients":[
        {"item": "Lobster","amount": 0.5},
        {"item": "Baguette","amount": 8},
        {"item": "Garlic","amount": 2}
      ]
},
{
      "id": 7,
      "name": "Potato and leaks soup",
      "type": "vegetarian",
      "ingredients":[
        {"item": "Water","amount": 0.5},
        {"item": "Potato","amount": 8},
        {"item": "Onion","amount": 2}
      ]
}

我想要实现的是从JSON文件中随机选择配方,例如7个配方。但条件是至少25%的配方应该是以下类型:因为在JSON文件中,每个食谱都标记了它的类型。
我使用的是random.sample()函数,那么我如何得到这里的条件呢?

import json
import random

with open('recipes.json') as json_file:
    data = json.load(json_file)

random = random.sample(data, 7)

for i in range(0, len(random)):
    print(random[i]["name"])
ni65a41a

ni65a41a1#

正如评论中所建议的:您可以仅从25%的样品的鱼食谱中选择,并且从非鱼食谱中选择其余的(对于“正好”25%的鱼食谱)或从所有食谱中选择其余的。
第一个建议大致如下:

import json
import random
import math

with open('recipes.json') as json_file:
    data = json.load(json_file)

total = 7
fish = random.sample(d for d in data if d['type']=='fish', ceil(total/4))
other = random.sample(d for d in data if d['type']!='fish', total - ceil(total/4)) 
recipes = fish + other  # you could of course shuffle them, if the type order needs to be random

for i in range(0, len(recipes)):  # note that `random` was renamed to `recipes`
    print(recipes[i]["name"])

random被重命名为recipes,因为“隐藏”内置和标准库名称是一个坏主意。一旦你这样做了,你将无法再轻松地使用random模块,而且任何阅读你代码的人都会感到困惑,包括未来的你。

相关问题