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
  Elegant way to apply each element of an array to a dataframe? sawtooth500 5 227 5 hours ago
Last Post: deanhystad
  list in dicitonary element problem jacksfrustration 3 626 Oct-14-2023, 03:37 PM
Last Post: deanhystad
  Error is finding mean of a list PythonBoy 4 845 Sep-11-2023, 02:38 PM
Last Post: PythonBoy
  Finding combinations of list of items (30 or so) LynnS 1 838 Jan-25-2023, 02:57 PM
Last Post: deanhystad
  Find (each) element from a list in a file tester_V 3 1,157 Nov-15-2022, 08:40 PM
Last Post: tester_V
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,738 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  functional LEDs in an array or list? // RPi user Doczu 5 1,523 Aug-23-2022, 05:37 PM
Last Post: Yoriz
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,162 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
Question Finding string in list item jesse68 8 1,801 Jun-30-2022, 08:27 AM
Last Post: Gribouillis
  How to find the second lowest element in the list? Anonymous 3 1,908 May-31-2022, 01:58 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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