如何定义一个二维数组?

新手上路,请多包涵

我想定义一个没有初始化长度的二维数组,如下所示:

 Matrix = [][]

但这给出了一个错误:

IndexError:列表索引超出范围

原文由 Masoud Abasian 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 869
2 个回答

您在技术上试图索引一个未初始化的数组。在添加项目之前,您必须先用列表初始化外部列表; Python 将此称为“列表理解”。

 # Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]

#您现在可以将项目添加到列表中:

 Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid

请注意,矩阵主要是“y”地址,换句话说,“y 索引”位于“x 索引”之前。

 print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!

尽管您可以随意命名它们,但如果您对内部和外部列表都使用“x”并且想要一个非方形矩阵,我会以这种方式查看它以避免索引可能出现的一些混淆。

原文由 Manny D 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你真的想要一个矩阵,你最好使用 numpynumpy 中的矩阵运算最常使用二维数组类型。创建新数组的方法有很多种;最有用的函数之一是 zeros 函数,它采用形状参数并返回给定形状的数组,并将值初始化为零:

 >>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

以下是创建二维数组和矩阵的其他一些方法(为了紧凑而删除了输出):

 numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy 提供了一个 matrix 类型,但 不再推荐 使用 它,将来可能会从 numpy 中删除。

原文由 senderle 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题