'Avoid IndexError with if statemanet
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
Solution 1:[1]
Your code works if you rename cidex+1 into cidx+1
also i think you want >= 0 instead of > 0if ridx-1 > 0 --> if ridx-1 >= 0
or you'll be missing the first index
Solution:
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
