You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的random.sample()按条件选食谱:至少25%为鱼类

如何随机选取满足fish类型占比至少25%的7个食谱?

问题背景

我有一个存储食谱的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%的食谱类型为fish的条件。目前使用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"])

解决方案

要满足fish类型占比至少25%的要求,首先计算7个食谱中最少需要的fish数量:7×25%=1.75,向上取整为至少2个fish类型食谱。我们可以通过拆分食谱类别、分别选取再合并的方式实现约束:

修改后的代码

import json
import random

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

# 将食谱拆分为fish类和非fish类
fish_recipes = [recipe for recipe in data if recipe["type"] == "fish"]
other_recipes = [recipe for recipe in data if recipe["type"] != "fish"]

# 计算最少需要的fish食谱数量(向上取整)
min_fish = 2  # 等价于 math.ceil(7 * 0.25)

# 先检查是否有足够的fish食谱满足要求
if len(fish_recipes) < min_fish:
    raise ValueError(f"fish类型食谱数量不足,至少需要{min_fish}个,但当前只有{len(fish_recipes)}个")

# 随机确定选取的fish数量:范围从min_fish到最多可选取的数量(不超过fish总数和7)
num_fish = random.randint(min_fish, min(len(fish_recipes), 7))
num_other = 7 - num_fish

# 检查非fish类食谱数量是否足够
if len(other_recipes) < num_other:
    raise ValueError(f"非fish类型食谱数量不足,需要{num_other}个,但当前只有{len(other_recipes)}个")

# 分别随机选取对应数量的食谱
selected_fish = random.sample(fish_recipes, num_fish)
selected_other = random.sample(other_recipes, num_other)

# 合并并打乱顺序,保证整体随机性
final_recipes = selected_fish + selected_other
random.shuffle(final_recipes)

# 输出结果
for recipe in final_recipes:
    print(recipe["name"])

代码关键点说明

  • 拆分类别:先把食谱分成fish和非fish两类,方便单独控制选取数量
  • 数量约束:强制保证至少选取2个fish食谱,满足25%的占比要求
  • 边界检查:提前校验两类食谱的数量是否满足选取需求,避免运行时出错
  • 随机灵活性:fish的选取数量在最小要求到最大可能范围内随机,既满足约束又保留随机性
  • 打乱顺序:合并后打乱列表,避免结果中fish食谱集中在开头的情况

内容的提问来源于stack exchange,提问作者Shitpost12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:41:47