Allan
Allan

Reputation: 47

Python | extracting elements from 2D array

I am not even sure how to word my question due to me being quite new to python. The basic concept of what I want to accomplish is to be able to search for something in a 2D array and retrieve the right value as well as the values associated with that value (sorry for my bad explanation)

e.g.

array=[[1,a,b],[2,x,d],[3,c,f]]

if the user wants to find 2, I want the program to retrieve [2,x,d] and if possible, put that into a normal (1D) array. Likewise, if the user searches for 3, the program should retrieve [3,c,f].

Thank you in advance (and if possible I want a solution that does not involve numpy)

Upvotes: 2

Views: 2008

Answers (4)

Jacques Gaudin
Jacques Gaudin

Reputation: 16958

Try something like :

def find(value, array):
    for l in array:
        if l[0]==value:
            return l

or if you want to learn more :

array[list(zip(*array))[0].index(value)]

Upvotes: 1

Tony Babarino
Tony Babarino

Reputation: 3405

You can use a dictionary if that fits in your problem:

>>> dict={1:['a','b'],2:['x','d'],3:['c','f']}
>>> dict[2]
['x', 'd']

It's more effective then searching linearly for the right index in every list.

Upvotes: 1

Sawel
Sawel

Reputation: 1009

You can do a simple for loop, and use the built-in in statement:

def retrieve_sub_array(element):
 for sub_array in array:
  if element in sub_array:
   return sub_array

Upvotes: 1

Work of Artiz
Work of Artiz

Reputation: 1090

Maybe something like this ?

def search(arr2d, value):
     for row in arr2d:
         if row[0] == value:
             return row

Upvotes: 1

Related Questions