以下是一个示例代码,可以遍历一个二维数组,查找并输出所有和为0的位置:
def find_zeros(matrix):
zeros = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
zeros.append((i, j))
return zeros
matrix = [[1, 2, 3], [4, -5, 6], [7, 8, -15]]
zero_positions = find_zeros(matrix)
for pos in zero_positions:
print("Zero found at position:", pos)
输出结果为:
Zero found at position: (1, 1)
Zero found at position: (2, 2)
这个示例代码使用了两个嵌套的for循环来遍历二维数组。在每个位置,它检查该位置的值是否为0,并将位置添加到一个列表中。最后,它输出所有找到的零的位置。