简体   繁体   中英

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. x and y are the coordinates of 1 in the matrix, whose POV this code is of. 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 . 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 = [
    [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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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