简体   繁体   中英

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)

eg

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)

Maybe something like this ?

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM