003《Python数据分析、挖掘与可视化(第2版)》/模拟生成考生志愿填报信息.py
from json import dump
from random import randint, sample, shuffle

# 所有选考科目
courses = ('物理', '化学', '生物', '历史', '地理', '思想政治')
# 存放考生志愿填报数据,格式为{'考生1':(位次, '选科情况','志愿1', '志愿2', ..., '志愿96')}
data = {}
# 假设有10000个考生,每个考生可以报96个志愿,共有1000个志愿可以选择
N, M, total = 10000, 96, 1000
# 生成考生位次
positions = list(range(1, N+1))
shuffle(positions)

for i in range(1, N+1):
    # 当前考生的选考科目
    my_choices = '+'.join(sample(courses, 3))
    # 当前考生填报的M个平行志愿,每个志愿不一样
    zhiyuan = tuple(f'志愿{i}' for i in sample(range(1,total+1),M))
    data[f'考生{i}'] = (positions.pop(), my_choices,) + zhiyuan

with open('考生位次选科与志愿填报.json', 'w', encoding='utf8') as fp:
    # 写入文件,保存
    dump(data, fp, ensure_ascii=False, indent='    ')