如何在多维数组中查找索引?

2024-09-28 05:44:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有回路

for x in multidimensional_array:  
    # do something here 

我能找到I,j,这样x=多维数组[I][j]吗


Tags: inforhere数组arraydosomethingmultidimensional
3条回答

在Python中迭代多维列表时,将得到一系列列表,而不是这些列表的元素。例如,以下代码:

for i in [[1, 2, 3], [4, 5, 6]]:
    print(i)

将输出以下内容:

[1, 2, 3]
[4, 5, 6]

遍历多维列表的一个好方法是使用嵌套循环,如以下示例中所示:

stuff = [[1, 2, 3], [4, 5, 6]]

for i in range(len(stuff)):
    iList = stuff[i]
    for j in range(len(iList)):
        jElement = iList[j]
        print("At i=" + str(i) + " and j=" + str(j) + ", we find " + str(jElement))

将打印:

At i=0 and j=0, we find 1
At i=0 and j=1, we find 2
At i=0 and j=2, we find 3
At i=1 and j=0, we find 4
At i=1 and j=1, we find 5
At i=1 and j=2, we find 6

为了找到元素x的索引,可以使用list.index函数:

def find(multi, x):
    for i in range(len(multi)):
        nested = multi[i]
        try:
            return i, nested.index(x)
        except ValueError:
            pass
    raise ValueError("Element not found")

简单嵌套循环:

for row in range(len(multidimensional_array)):
    for column in range(len(multidimensional_array[row])):
        if multidimensional_array[row][column] == x:
            <hand the row and column information>
            break

这将搜索2D列表中的所有列表,然后搜索该内部列表中的每个项目,如果行、列位置的项目与您的“x”匹配,则对其进行处理

for(Row in multiArray){
   for(Col in Row){
      //Col is x in this case
   }
} 
//A java example would be like this
int[][] multiArray = {(blabla),(blabla)}
for(int[] row: multiArray){
   for(int col: row){
      print(col); // Col is the x that you are looking for.
   }
}

相关问题 更多 >

    热门问题