这是我在 StackOverflow 上发布的第二个问题,涉及 Python/Numpy 编码。
我觉得肯定有某种函数可以执行伪代码:
np.random.choice([a[i-1,j],a[i+1,j],a[i,j-1],a[i,j+1]])==0 = 9
本质上,我希望随机函数选择与我相邻的单元格(上、下、左、右),值为 0,并将所述单元格替换为 9
不幸的是,我知道为什么我输入的代码是非法的。语句的前半部分返回 True/False bool 值,因为我使用了比较/检查运算符。我无法将其设置为值 9。
如果我将代码加载分成两个代码,并使用带有 random.choice 的 if 语句(查看等于零的相邻元素),那么在此之后,我需要某种函数或定义来记忆哪个随机生成器最初选择的单元格(上下左右),然后我可以将其设置为 9。
亲切的问候,
编辑:我也可以附上示例代码,这样您就可以简单地运行它(我包括我的错误)
a = np.empty((6,6,))
a[:] = 0
a[2,3]=a[3,3]=a[2,4] = 1
for (i,j), value in np.ndenumerate(a):
if a[i,j]==1:
np.random.choice([a[i-1,j],a[i+1,j],a[i,j-1],a[i,j+1]])==0 = 9
最佳答案
您可以从映射到 2D 数组中特定坐标移动的一系列方向(上、下、左、右)中进行选择,如下所示:
# generate a dataset
a = np.zeros((6,6))
a[2,3]=a[3,3]=a[2,4] = 1
# map directions to coordinate movements
nesw_map = {'left': [-1, 0], 'top': [0, 1], 'right': [1,0], 'bottom': [0,-1]}
directions = nesw_map.keys()
# select only those places where a == 1
for col_ind, row_ind in zip(*np.where(a == 1)): # more efficient than iterating over the entire array
x = np.random.choice(directions)
elm_coords = col_ind + nesw_map[x][0], row_ind + nesw_map[x][1]
if a[elm_coords] == 0:
a[elm_coords] = 9
请注意,这不会执行任何类型的边界检查(因此,如果 1
出现在边缘,您可能会选择“脱离网格”的项目,这将导致错误)。
关于python - 引用数组的条件随机元素并替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29168646/