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)
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。
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)