引用数组的条件随机元素并替换它

Referencing a conditional random element of an array and replacing it

这是我在 Whosebug 上提出的第二个问题 post,与 Python/Numpy 中的编码有关。

我觉得肯定有某种函数可以执行伪代码:

np.random.choice([a[i-1,j],a[i+1,j],a[i,j-1],a[i,j+1]])==0 = 9

本质上,我希望随机函数 select 与我相邻的单元格(上、下、左、右)的值为 0,并用 9

替换所述单元格

Unfo运行最近,我知道为什么我输入的代码是非法的。语句的前半部分 returns 是 True/False 布尔值,因为我使用了 comparison/checking 运算符。我无法将其设置为值 9。

如果我将代码加载分成两个代码并使用带有 random.choice 的 if 语句(查看等于零的相邻元素),那么在这之后,我将需要某种函数或定义来回忆最初是哪个单元格(左上或右上)随机生成器 select,然后我可以将其设置为 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

您可以 select 从一系列方向(上、下、左、右)映射到二维数组中的特定坐标移动,如下所示:

# 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 出现在边缘,您可能 select 一个项目 "off the grid" 这将导致错误).

这是获得所需内容的最 "basic" 方式(添加 try/except 语句提供错误检查,因此您可以防止任何不需要的错误):

import random,numpy
a = numpy.empty((6,6,))
a[:] = 0
a[2,3]=a[3,3]=a[5,5] = 1

for (i,j), value in numpy.ndenumerate(a):
    var = 0
    if a[i,j]==1:
        while var==0:
            x=random.randrange(0,4)                   #Generate a random number
            try:      
                if x==0 and a[i-1,j]==0:              
                    a[i-1,j] =9                       #Do this if x = 0
                elif x==1 and a[i+1,j]==0:            
                    a[i+1,j] =9                       #Do this if x = 1
                elif x==2 and a[i,j-1]==0:             
                    a[i,j-1] =9                       #Do this if x = 2
                elif x==3 and a[i,j+1]==0:            
                    a[i,j+1] =9                       #Do this if x = 3
                var=1
            except:
                var=0

print a