I have a "matrix" (list of lists) with information for each coordinates. I want to be able to get the neighbors of each element if possible. If not, return None
matrix = [ [{"name":"A"},{"name":"B"}],
[{"name":"C"},{"name":"D"}]]
for ridx, slotRow in enumerate(matrix):
for cidx, slotData in enumerate(slotRow):
n ={
"up": matrix [ridx-1][cidx] if ridx-1 > 0 else None,
"down": matrix[ridx 1][cidx] if ridx 1 < len(matrix) else None,
"left": matrix[ridx][cidx-1] if cidx-1 > 0 else None,
"right": matrix[ridx][cidx 1] if cidex 1 < len(matrix[ridx]) else None
}
print(n)
Is there a way to achieve this without getting an IndexError or without having a Try/Except for each neighbour? Up and Left are ok. The index larger than length are the problem
CodePudding user response:
You should check that ridx-1
and cidx-1
are greater than or equal to 0, as zero is the first valid index. So:
matrix = [[{"name":"A"},{"name":"B"}],
[{"name":"C"},{"name":"D"}]]
for ridx, slotRow in enumerate(matrix):
for cidx, slotData in enumerate(slotRow):
n = {
"up": matrix [ridx-1][cidx] if ridx-1 >= 0 else None,
"down": matrix[ridx 1][cidx] if ridx 1 < len(matrix) else None,
"left": matrix[ridx][cidx-1] if cidx-1 >= 0 else None,
"right": matrix[ridx][cidx 1] if cidx 1 < len(matrix[ridx]) else None
}
print(n)
Btw, check the spelling for the last cidx 1
.
CodePudding user response:
Your code works if you rename cidex 1
into cidx 1
also i think you want >= 0
instead of > 0
if ridx-1 > 0
--> f ridx-1 >= 0
or you'll be missing the first index