在这段代码中,m
是一个矩阵。x
和y
是矩阵中1的坐标,此代码是其POV的坐标。我创建了一个嵌套在另一个循环中的循环,该循环将矩阵中的每个元素添加到由x
和指定的元素周围y
,该列表由和指定neighbors
。我从邻居列表中选取一个随机元素。我怎么可以把这个元素,并找到它的索引(或它x
与y
矩阵中的位置)m
?
m = [
[0, 0 ,0 ,0],
[0 ,2 ,0 ,0],
[0 ,1, 0 ,0],
[0 ,0 ,0, 0]
]
x = 1 # x coordinate of 1 in the matrix
y = 2 # y coordinate of 1 in the matrix
neighbors = [] # empty list regarding the neighbors of 1 which will be generated with the loop
for x_elem in (x-1, x, x+1):
for y_elem in (y-1, y, y+1):
element = m[y_elem][x_elem] # getting the element in m
neighbors.append(element) # taking that element and appending it to the neighbors list
if m[y_elem][x_elem] == m[y][x]: # if the element is the same as itself (aka 1), remove it from neighbors
neighbors.remove(m[y_elem][x_elem])
print(neighbors) # [0, 0, 0, 2, 0, 0, 0, 0]
c = random.choice(neighbors) # take a random element of the neighbors
print(c)
#how to get c's index in the 2d array m
尝试附加此逻辑。因为我们只检查邻居,所以逻辑要简单得多。主要逻辑是在计算邻居时捕获x和y索引,并将其附加到List(List),其中内部列表具有三个元素,即第一个元素,第二个x索引和第三个y索引。然后,一个简单的打印语句就可以满足期望。
x = 1 # x coordinate of 1 in the matrix
y = 2 # y coordinate of 1 in the matrix
neighborsArr = []
for x_elem in (x-1, x, x+1):
for y_elem in (y-1, y, y+1):
element = m[y_elem][x_elem] # getting the element in m
if m[y_elem][x_elem] != m[y][x]: # if the element is the same as itself (aka 1), remove it from neighbors
neighborsArr.append([element,x_elem, y_elem])
print(neighborsArr)
# [[0, 0, 1], [0, 0, 2], [0, 0, 3], [2, 1, 1], [0, 1, 3], [0, 2, 1], [0, 2, 2], [0, 2, 3]]
c = random.choice(neighborsArr) # take a random element of the neighbors
print(c)
# [0, 2, 2]
print(c[0])
# 0
print("neighbour element : ", c[0], "\tx_index: ",c[1], "\ty_index :", c[2])
# neighbour element : 0 x_index: 2 y_index : 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句