繁体   English   中英

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

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

在这段代码中, m是一个矩阵。 xy是 1 在矩阵中的坐标,此代码是其 POV。 我创建了一个嵌套在另一个循环中的循环,它将包围由xy指定的元素的矩阵中的每个元素添加到名为neighbors的列表中。 我从邻居列表中随机取一个元素。 如何获取这个元素并在矩阵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

尝试附加此逻辑。 更简单的逻辑,因为我们只检查邻居。 主要逻辑是在计算邻居时捕获 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.

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