如果我有循环
for x in multidimensional_array:
# do something here
我能找到i,j这样x = multidimensional_array [i] [j]?
答案 0 :(得分:0)
在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")
答案 1 :(得分:0)
简单的嵌套循环:
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列表中的所有列表,然后搜索该内部列表中的每个项目,如果该行,列位置的项目与您的&#39; x&#39;是,用它做点什么。
答案 2 :(得分:-1)
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.
}
}