Python:如何生成仅由特定数字-1、0、1组成的随机数组?

3no*_*tur 1 python arrays random

Python 中是否有一种标准方法来生成一个数组(大小为 15),其中随机放置三个 1 和四个 -1,其余数组项为 0?

这种数组的一个例子是

0 0 0 0 1 1 0 -1 1 -1 -1 0 0 0 -1
Run Code Online (Sandbox Code Playgroud)

tla*_*tla 6

使用random.sample

from random import sample
array = sample([1, -1, 0], 15, counts=[3, 4, 8])
print(array)
Run Code Online (Sandbox Code Playgroud)

请注意,该counts参数需要 Python 3.9。

使用random.shuffle

from random import shuffle
array = 3 * [1] + 4 * [-1] + 8 * [0]
shuffle(array)
print(array)
Run Code Online (Sandbox Code Playgroud)

输出示例:

[0, -1, 0, 0, 1, -1, -1, 0, 0, 0, -1, 1, 0, 0, 1]
Run Code Online (Sandbox Code Playgroud)