[英]np.random.choice exclude certain numbers?
I'm supposed to create code that will simulate a d20 sided dice rolling 25 times using np.random.choice
.我应该创建代码来模拟使用
np.random.choice
滚动 25 次的 d20 面骰子。
I tried this:我试过这个:
np.random.choice(20,25)
but this still includes 0's which wouldn't appear on a dice.但这仍然包括不会出现在骰子上的 0。
How do I account for the 0's?我如何解释0?
import numpy as np
np.random.seed(42) # for reproducibility
result = np.random.choice(np.arange(1, 21), 50)
print(result)
Output输出
[ 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]
The above code draws numbers from 0 to 20 both inclusive.上面的代码绘制从 0 到 20 的数字。 To understand why, you could check the documentation of np.random.choice , in particular on the first argument:
要了解原因,您可以查看np.random.choice的文档,尤其是第一个参数:
a : 1-D array-like or int
a : 一维数组或 int
If an ndarray, a random sample is generated from its elements.
如果是 ndarray,则从其元素生成随机样本。 If an int, the random sample is generated as if a was np.arange(n)
如果是 int,则生成随机样本,就好像 a 是 np.arange(n)
np.random.choice() 将可能的选择数组作为它的第一个参数(如果给定 int,它的工作方式类似于 np.arrange),因此您可以使用 list(range(1, 21)) 来获得您想要的输出
+1
np.random.choice(20,25) + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.