Finding an element in a 1d list in a 2d array - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Finding an element in a 1d list in a 2d array (/thread-27930.html) |
Finding an element in a 1d list in a 2d array - lionrocker221 - Jun-27-2020 Hello, In this code, neighbors is a list that is generated from m , from the point of view of "1" in the matrix. I'm trying to take a random element from neighbors and find the index of that element in the 2d array m .import numpy as np import random 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 = 1 # 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 map[y_elem][x_elem] == map[y][x]: # if the element is the same as itself (aka 1), remove it from neighbors neighbors.remove(map[y_elem][x_elem]) c = random.choice(neighbors) # take a random element fo the neighbors . . . #how to get c's index in the 2d array mInstead of trying to get the element from the index in m , how can I reverse this process and find the index from the element? Neighbors, in this case, would be [0, 0, 0, 2, 0, 0, 0, 0], elements that stem from the matrix m] .
|