简体   繁体   中英

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 .

I tried this:

np.random.choice(20,25)

but this still includes 0's which wouldn't appear on a dice.

How do I account for the 0's?

Use np.arange :

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. To understand why, you could check the documentation of np.random.choice , in particular on the first argument:

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)

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

+1

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM