[英]How can I get the index of an element in a matrix from a list that is generated from that matrix?
在這段代碼中, m
是一個矩陣。 x
和y
是 1 在矩陣中的坐標,此代碼是其 POV。 我創建了一個嵌套在另一個循環中的循環,它將包圍由x
和y
指定的元素的矩陣中的每個元素添加到名為neighbors
的列表中。 我從鄰居列表中隨機取一個元素。 如何獲取這個元素並在矩陣m
中找到它的索引(或它的x
和y
位置)?
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 索引,並將 append 捕獲到一個 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.