I have the following list:
grid = [[2, 6, 8, 6, 9], [2, 5, 5, 5, 0], [1, 3, 8, 8, 7], [3, 2, 0, 6, 9], [2, 1, 4,5,8], [5, 6, 7, 4, 7]]
and I use fowling for loop for traversing each element for grid list ->
for i in xrange(len(grid[i])):
for j in xrange(len(grid[j])):
print grid[i][j]
print "\n"
But , it don't show last row of list i.e [5,6,7,4,7]
So, which is proper war in python to Travers in 2D List?
解决方案
The proper way to traverse a 2-D list is
for row in grid:
for item in row:
print item,
The for loop in Python, will pick each items on every iteration. So, from grid 2-D list, on every iteration, 1-D lists are picked. And in the inner loop, individual elements in the 1-D lists are picked.
If you are using Python 3.x, please use the print as a function, not as a statement, like this
for row in grid:
for item in row:
print(item, end = " ")
print()
Output
2 6 8 6 9
2 5 5 5 0
1 3 8 8 7
3 2 0 6 9
2 1 4 5 8
5 6 7 4 7
But, in case, if you want to change the element at a particular index, then you can do
for row_index, row in enumerate(grid):
for col_index, item in enumerate(row):
gird[row_index][col_index] = 1 # Whatever needs to be assigned.