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

Python如何按预设分类占比生成指定总数量的测验题目集

实现方案

核心逻辑采用「基础取整+余数优先分配」规则,保证总题量完全匹配输入值,同时和预设占比的误差最小。

完整可运行代码

import random

# 分类占比配置(数值为百分比)
category_ratio = {
    "Math": 30,
    "Sport": 14,
    "Citys": 6,
    "Games": 3,
    "Inventions": 3
}

# 各分类题库,可替换为你的真实题目数据
category_question_pool = {
    "Math": [f"数学题{i}" for i in range(1000)],
    "Sport": [f"体育题{i}" for i in range(1000)],
    "Citys": [f"城市题{i}" for i in range(1000)],
    "Games": [f"游戏题{i}" for i in range(1000)],
    "Inventions": [f"发明题{i}" for i in range(1000)],
}

final_questions = []
total_amount = int(input("请输入总题量:"))

# 第一步:计算各分类基础题量
# 兼容占比总和不为100%的情况,如需严格100%可直接替换total_ratio为100
total_ratio = sum(category_ratio.values())
category_count = {}
remainder_list = []

for cate, ratio in category_ratio.items():
    exact_num = total_amount * ratio / total_ratio
    base_num = int(exact_num)
    category_count[cate] = base_num
    # 存储小数部分用于余数分配
    remainder = exact_num - base_num
    remainder_list.append((-remainder, cate))

# 第二步:分配剩余题量,优先给小数部分大的分类加1,保证总题量完全匹配
remaining_count = total_amount - sum(category_count.values())
remainder_list.sort()
for i in range(remaining_count):
    _, cate = remainder_list[i]
    category_count[cate] += 1

# 第三步:从对应分类题库抽取指定数量题目
for cate, count in category_count.items():
    selected_questions = random.sample(category_question_pool[cate], count)
    final_questions.extend(selected_questions)

# 可选:打乱总题顺序
random.shuffle(final_questions)

# 验证输出
print(f"实际生成总题量:{len(final_questions)}")
print(f"各分类题量分布:{category_count}")

效果验证

输入总题量为40时,输出的各分类题量总和恰好为40,和预设占比的偏差控制在1题以内。

自定义调整说明

  • 如需直接生成题目而非从题库抽取,替换第三步的抽取逻辑为你的题目生成规则即可
  • 不需要打乱总题顺序的话,删除random.shuffle(final_questions)行即可
  • 确认占比总和固定为100%的话,可删除total_ratio = sum(category_ratio.values())行,将exact_num = total_amount * ratio / total_ratio修改为exact_num = total_amount * ratio / 100

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:24:06