简体   繁体   English

如何从从该矩阵生成的列表中获取矩阵中元素的索引?

[英]How can I get the index of an element in a matrix from a list that is generated from that matrix?

in this code, m is a matrix.在这段代码中, m是一个矩阵。 x and y are the coordinates of 1 in the matrix, whose POV this code is of. xy是 1 在矩阵中的坐标,此代码是其 POV。 I created a loop that is nested within another loop, that adds each element in the matrix that surrounds an element specified by x and y to a list called neighbors .我创建了一个嵌套在另一个循环中的循环,它将包围由xy指定的元素的矩阵中的每个元素添加到名为neighbors的列表中。 I take a random element from the list of neighbors.我从邻居列表中随机取一个元素。 How can I take this element and find its index (or its x and y position) in the matrix m ?如何获取这个元素并在矩阵m中找到它的索引(或它的xy位置)?

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

Try appending this logic.尝试附加此逻辑。 Much simpler logic as we are only checking for neighbours.更简单的逻辑,因为我们只检查邻居。 The main logic is to capture and x and y index when neighbours are calculated and append that to a List(List) where internal list has three elements first element second x index and third y index.主要逻辑是在计算邻居时捕获 x 和 y 索引,并将 append 捕获到一个 List(List) ,其中内部列表具有三个元素第一个元素第二个 x 索引和第三个 y 索引。 And then a simple print statement can satisfy the expectation.然后一个简单的打印语句就可以满足期望。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM