简体   繁体   English

Python | 从2D数组中提取元素

[英]Python | extracting elements from 2D array

I am not even sure how to word my question due to me being quite new to python. 由于我是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) 我要完成的工作的基本概念是能够在2D数组中搜索某些内容并检索正确的值以及与该值关联的值(对不起,我的解释不好)

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. 如果用户要查找2 ,我希望程序检索[2,x,d]并在可能的情况下将其放入常规(1D)数组中。 Likewise, if the user searches for 3 , the program should retrieve [3,c,f] . 同样,如果用户搜索3 ,则程序应检索[3,c,f]

Thank you in advance (and if possible I want a solution that does not involve numpy) 在此先感谢您(如果可能,我需要一个不涉及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: 您可以执行一个简单的for循环,并使用内置的in语句:

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. 然后,在每个列表中线性搜索正确的索引会更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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