Gro*_* Ni -1 python random numpy
我有一个 2D 布尔数组,我想生成一个随机位置1。
array([[0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 0, 0, 0, 1],
[0, 1, 1, 1, 0, 0, 1, 1]])
Run Code Online (Sandbox Code Playgroud)
输出示例:
(2,2)
Run Code Online (Sandbox Code Playgroud)
像这样的事情可能会起作用:
import numpy as np
l = np.array([[0, 0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 0, 0, 0, 1],
[0, 1, 1, 1, 0, 0, 1, 1]])
random = np.random.choice(np.sum(l))
np.argwhere(l)[random]
Run Code Online (Sandbox Code Playgroud)
结果:
[0, 4]