I'm currently working on a Python 3 project that involves iterating several times through a list of lists, and I want to write a code that skips over specific indices of this list of lists. The specific indices are stored in a separate list of lists. I have written a small list of lists, grid and the values I do not want to iterate over, coordinates:
grid = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]
coordinates = [[0, 2], [1, 1], [2, 0]]
Basically, I wish to skip over each 1 in grid.
I tried the following code to no avail:
for row in grid:
for value in row:
for coordinate in coordinates:
if coordinate[0] != grid.index(row) and coordinate[1] != row.index(value):
row[value] = 4
print(grid)
The expected output is: [[4, 4, 1], [4, 1, 4], [1, 4, 4]]
After executing the code with, I am greeted with ValueError: 1 is not in list.
I have 2 questions:
Why am I being given this error message when each
coordinateincoordinatescontains a 0th and 1st position?Is there a better way to solve this problem than using for loops?
CodePudding user response:
There are two issues with your code.
The
rowcontains a list of integers, andvaluecontains values in those rows. The issue is that you need access to the indices of these values, not the values themselves. The way that you've set up your loops don't allow for that..index()returns the index of the first instance of the argument passed in; it is not a drop-in replacement for using indexing with brackets.
Here is a code snippet that does what you've described, fixing both of the above issues:
grid = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]
coordinates = [[0, 2], [1, 1], [2, 0]]
for row in range(len(grid)):
for col in range(len(grid[row])):
if [row, col] not in coordinates:
grid[row][col] = 4
print(grid) # -> [[4, 4, 1], [4, 1, 4], [1, 4, 4]]
By the way, if you have a lot of coordinates, you can make it a set of tuples rather than a 2D list so you don't have to iterate over the entire list for each row / column index pair.
CodePudding user response:
grid = [
[0, 0, 1],
[0, 1, 0],
[1, 0, 0]]
coordinates = [[0, 2], [1, 1], [2, 0]]
for y, row in enumerate(grid):
for x, value in enumerate(row):
if [x, y] in coordinates or value != 1:
grid[y][x] = 4
print(grid)
