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
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.
}
}
在Python中迭代多维列表时,将得到一系列列表,而不是这些列表的元素。例如,以下代码:
将输出以下内容:
遍历多维列表的一个好方法是使用嵌套循环,如以下示例中所示:
将打印:
为了找到元素
x
的索引,可以使用list.index
函数:简单嵌套循环:
这将搜索2D列表中的所有列表,然后搜索该内部列表中的每个项目,如果行、列位置的项目与您的“x”匹配,则对其进行处理
相关问题 更多 >
编程相关推荐