2

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)

4
  • What do you want as a result if you search for 2 and your list looks like this? [[1,a,b],[2,x,d],[2,c,f]]? Will you always search for the first element in these lists, or could you, say, search for a, too? Commented Apr 6, 2016 at 20:49
  • the first element will be unique (a number used to identify the following elements), as for the second question: no - only the first element in used when searching for the group of elements Commented Apr 6, 2016 at 22:00
  • One more question then. Will the numbers be in order and with no gaps? For example, 1, 2, 3, ..., or could you get 1, 3, 10, or even 1, 4, 2, ...? Commented Apr 6, 2016 at 22:04
  • it won't necessarily be in numerical order, it can be random. Thank you for asking but I have found a solution so a reply won't be necessary. Commented Apr 6, 2016 at 22:15

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

Maybe something like this ?

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

Comments

1

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.

Comments

1

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.