如何使用 np.random.randint() 掷 n 个骰子,注意每个骰子的面数可能不同,由向量 f 表示

How to use np.random.randint() to roll n dice, noting that each has a potentially different number of faces denoted by a vector f

我正在尝试模拟单掷 n 个骰子,其中每个骰子都可能有 f 个面。例如,如果 =[2,5,7],则掷三个面为 2、5、7 的骰子。谢谢!

我得到它来处理这个:

    f=[3,4,5]
    outcomes= []
    for i in f:
        out = 1 + np.random.randint(i, size = len(f) )
        outcomes.append(out)

谢谢!

你可以在没有显式循环的情况下做到这一点。在此示例中,我将使用 numpy 1.17 中引入的 "new" numpy random API。在新的API中,使用生成器的integers方法生成随机整数;它对应于旧的 randint 方法:

In [22]: rng = np.random.default_rng()                                          

In [23]: f = np.array([2, 5, 7])                                                

In [24]: rng.integers(1, f + 1)                                                 
Out[24]: array([2, 4, 6])

要在一次调用中重复该过程 n 次,请使用 size 参数:

In [30]: n = 8                                                                  

In [31]: rng.integers(1, f + 1, size=(n, 3))                                    
Out[31]: 
array([[1, 3, 4],
       [1, 1, 5],
       [1, 3, 1],
       [2, 3, 1],
       [2, 2, 4],
       [2, 4, 2],
       [1, 1, 3],
       [2, 1, 7]])