np.random.choice是否排除某些数字?

2024-06-11 14:38:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该创建代码,用np.random.choice模拟一个d20面的骰子滚动25次

我试过这个:

np.random.choice(20,25)

但这仍然包括不会出现在骰子上的0

如何解释0


Tags: 代码nprandom骰子choiced20
3条回答

np.random.choice()的第一个参数是一个可能的选项数组(如果给定int,它的工作方式类似于np.arrange),因此您可以使用list(range(1,21))获得所需的输出

使用np.arange

import numpy as np

np.random.seed(42)  # for reproducibility

result = np.random.choice(np.arange(1, 21), 50)
print(result)

输出

[ 7 20 15 11  8  7 19 11 11  4  8  3  2 12  6  2  1 12 12 17 10 16 15 15
 19 12 20  3  5 19  7  9  7 18  4 14 18  9  2 20 15  7 12  8 15  3 14 17
  4 18]

上述代码从0到20(包括0和20)绘制数字。要了解原因,可以查看np.random.choice的文档,特别是第一个参数:

a : 1-D array-like or int

If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n)

+1

np.random.choice(20,25) + 1

相关问题 更多 >