简体   繁体   English

在python中的2D列表(矩阵)范围内进行迭代

[英]Iterating within bounds of a 2D list (matrix) in python

I would like to iterate over a 2D list. 我想遍历2D列表。 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 .: 但这给了我一个IndentationError

Thanks 谢谢

EDIT: what if i want to set bounds for x and y. 编辑:如果我想为x和y设置边界怎么办。 Say I have a 4x4 matrix(using list to represent it). 假设我有一个4x4矩阵(使用列表表示)。 For a given element I want to get 3x3 matrix around it, but i want to remain within the bounds of the original matrix. 对于给定的元素,我想在其周围获得3x3矩阵,但我希望保持在原始矩阵的范围内。 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. 假设我在(3,1),取x = range(3-2, 3+3) = [1,2,3,4,5] y = range(1-2,1+3) = [-1, 0, 1, 2, 3] x = range(3-2, 3+3) = [1,2,3,4,5]y = range(1-2,1+3) = [-1, 0, 1, 2, 3]将我带到原始矩阵的范围之外。

You can use itertools.product , or write a double-loop generator-expression like: 您可以使用itertools.product ,也可以编写一个双循环generator-expression,例如:

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: 另外,如果您实际上不需要索引,而仅需要遍历depth ,则可以执行以下操作:

for row in depth:
   for v in row:
      print

and even if you do need the indices, it is more pythonic to use enumerate : 即使您确实需要索引,使用enumerate还是更Python化:

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

Edit: 编辑:

If you want bounds you can use the min and max builtins : 如果您想要界线,则可以使用minmax内置函数:

for x in range( max(x_min,col-2), min(x_max,col+3) ):
    #do stuff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM