Python 中有没有办法更新字典中的多个随机值?

Is there a way in Python to update multiple random values in dictionary?

我正在开发一个时间表生成器,我需要随机放两天假。我想出了一个解决方案,但是我注意到 randinit 方法可以在一天中放两天假,所以这个选项对我不起作用。

import random

schedule = {1: "9:00 - 17:00", 2: "9:00 - 17:00", 3: "16:00 - 00:00", 4: "16:00 - 00:00", 5: "16:00 - 00:00", 6: "16:00 - 00:00", 7: "16:00 - 00:00"}
days_off = {random.randint(1, 7): "X", random.randint(1, 7): "X"}

schedule.update(days_off)

所以我认为应该有一种更简单的方法可以在不进行硬编码的情况下使其工作,但我真的找不到它。

感谢任何帮助!

您正在寻找的是 random.sample(),它允许您随机 select 来自给定总体的多个 不同 值:

for d in random.sample(range(1, 7+1), k=2):
    schedule[d] = "X"

另一个用 numpy 的答案:

import numpy as np
for day_off in np.random.choice(np.arange(7), size=2, replace=False):
    shedule[day_off + 1] = "X"