python - 在Python中的二维列表(矩阵)的范围内迭代

标签 python

我想迭代一个二维列表。我知道我可以通过以下方式做到这一点:

for j in range(columns):
     for i in range(rows):
        print depth[i][j],

但是有没有更漂亮的方式呢。我尝试过:

for (x in range(rows)) and (y in range(columns)):
     print(depth[x][y])

但这给了我一个IndentationError .:

谢谢

编辑: 如果我想设置 x 和 y 的界限怎么办?假设我有一个 4x4 矩阵(使用列表来表示它)。对于给定的元素,我想在它周围获得 3x3 矩阵,但我想保持在原始矩阵的范围内。假设我在 (3,1),取 x = range(3-2, 3+3) = [1,2,3,4,5]y = range(1-2,1+3) = [-1, 0, 1, 2, 3]会让我超出原始矩阵的范围。

最佳答案

您可以使用itertools.product ,或者编写一个双循环生成器表达式,例如:

for (i,j) in ( (i,j) for i in range(rows) for j in range(columns) ):
    print depth[i][j]

for d in ( depth[i][j] for i in range(rows) for j in range(columns) ): ...

此外,如果您实际上不需要索引,而只是为了迭代深度,您可以这样做:

for row in depth:
   for v in row:
      print

即使您确实需要索引,使用 enumerate 也更加Pythonic:

for row_index, row in enumerate(depth):
   for col_index, v in enumerate(row):
      print 'depth[%d][%d]=%s' % (row_index, col_index, v)

关于python - 在Python中的二维列表(矩阵)的范围内迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23166996/

相关文章:

python - 如何将参数传递给 Python 中的线程?

python - tkinter ttk.Combobox 下拉/展开并聚焦于文本

python - 无论 classifier.fit 中的步数如何,Tensorflow 都会返回相同的精度

python - Numpy 数组与权重求和

python - python 中的 RESTful API 请求 [tensorflow 服务]

python - 如何使用 Python 代码制作永久文件? - 复制它

python - 非阻塞 multiprocessing.connection.Listener?

python - 执行 Plotly Dash .exec 文件时出现 PyInstaller 错误

python - Python sklearn 中是否有用于非线性逻辑回归的模块?

python - 将带有时区的python日期时间转换为字符串