# 如何在 Python 中创建二维数组

## 列表推导式

``````>>> column, row = 3, 5
>>> array2D = [[0 for _ in range(row)] for _ in range(column)]
>>> array2D
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
``````

## 嵌套 `range` 方法

``````>>> column, row = 3, 5
>>> A = [range(row) for _ in range(column)]
>>> A
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
``````

``````>>> column, row = 3, 5
>>> A = [range(row) for _ in range(column)]
>>> A
[range(0, 5), range(0, 5), range(0, 5)]
``````

`range` 在 Python 3.x中更类似于 Python2.x 中的 `xrange`。Python 3.x 中的 `range` 类型数据是不可变的，因此，你不能为分配元素。

``````>>> A = [list(range(row)) for _ in range(column)]
>>> A
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
``````

### `[0]*n` 方法

``````>>> column, row = 3, 5
>>> A = [[0]*row for _ in range(column)]
>>> A
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
``````

## `numpy` 方法

``````>>> import numpy as np
>>> column, row = 3, 5
>>> np.zeros(column, row)
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
``````

``````>>> import numpy as np
>>> column, row = 3, 5
>>> np.ones((column, row))
array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
``````

``````>>> import numpy as np
>>> column, row = 3, 5
>>> np.empty((5,5))
array([[6.23042070e-307, 4.67296746e-307, 1.69121096e-306,
1.33511562e-306, 1.89146896e-307],
[7.56571288e-307, 3.11525958e-307, 1.24610723e-306,
1.37962320e-306, 1.29060871e-306],
[2.22518251e-306, 1.33511969e-306, 1.78022342e-306,
1.05700345e-307, 1.11261027e-306],
[1.11261502e-306, 1.42410839e-306, 7.56597770e-307,
6.23059726e-307, 1.42419530e-306],
[7.56599128e-307, 1.78022206e-306, 8.34451503e-308,
2.22507386e-306, 7.20705877e+159]])
``````
Notes