I would like to iterate over a 2D list. I understand that I can do this with:
for j in range(columns):
for i in range(rows):
print depth[i][j],
But is there a more beautiful way. I tried:
for (x in range(rows)) and (y in range(columns)):
print(depth[x][y])
But this given me an IndentationError
.:
Thanks
EDIT: what if i want to set bounds for x and y. Say I have a 4x4 matrix(using list to represent it). For a given element I want to get 3x3 matrix around it, but i want to remain within the bounds of the original matrix. Suppose I am at (3,1), taking x = range(3-2, 3+3) = [1,2,3,4,5]
and y = range(1-2,1+3) = [-1, 0, 1, 2, 3]
would take me outside the bounds of the original matrix.
You can use itertools.product , or write a double-loop generator-expression like:
for (i,j) in ( (i,j) for i in range(rows) for j in range(columns) ):
print depth[i][j]
or
for d in ( depth[i][j] for i in range(rows) for j in range(columns) ): ...
also, if you don't actually need the indices, but only to iterate over the values of depth
, you can do:
for row in depth:
for v in row:
print
and even if you do need the indices, it is more pythonic to use enumerate
:
for row_index, row in enumerate(depth):
for col_index, v in enumerate(row):
print 'depth[%d][%d]=%s' % (row_index, col_index, v)
This can be done with:
for depth in (depth[x][y] for x in range(rows) for y in range(columns)):
print depth
If you want bounds you can use the min
and max
builtins :
for x in range( max(x_min,col-2), min(x_max,col+3) ):
#do stuff
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.