Python Forum
Finding an element in a 1d list in a 2d array
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Finding an element in a 1d list in a 2d array
#1
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 m




Instead 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].
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sume Every 10 element in the list and Divided of Sum quest_ 7 148 Nov-27-2020, 10:58 AM
Last Post: perfringo
  Counting Element in Multidimensional List quest_ 1 96 Nov-25-2020, 10:00 PM
Last Post: quest_
  Adding List Element if Second part of the List Elements are the Same quest_ 3 129 Nov-25-2020, 04:33 PM
Last Post: bowlofred
  Choose an element from multidimensional array quest_ 2 77 Nov-25-2020, 12:59 AM
Last Post: quest_
  Removing element from list squall 6 188 Nov-22-2020, 09:34 PM
Last Post: jefsummers
  2d Array adds last element to entire list waiteup 2 105 Nov-19-2020, 08:25 PM
Last Post: bowlofred
  How to get index of minimum element between 3 & 8 in list Mekala 2 171 Nov-10-2020, 12:56 PM
Last Post: DeaD_EyE
  Problem printing last element from a list tester_V 3 200 Oct-30-2020, 04:54 AM
Last Post: tester_V
  finding element of specific field in pandas adjacency matrix amjass12 0 132 Oct-27-2020, 09:27 AM
Last Post: amjass12
  trouble with list array Milfredo 2 243 Sep-16-2020, 12:07 AM
Last Post: Milfredo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020