python - 在 Python 3 中有效地初始化大小为 n*m 的二维数组?

标签 python arrays python-3.x

我正在使用 Python 3 并尝试创建已知且固定大小的二维整数数组。我该怎么做?

我想到的数组是 Python 提供的 array.array,尽管我并不反对使用像 NumPy 这样的库。

我知道这可以通过列表来完成,但我想使用数组,因为它们的空间效率更高。现在,我正在以这种方式初始化列表,但我想用数组替换它:

my_list = [[ 0 for _ in range(height) ] for _ in range(.width)]

例如,在C中,我会这样写

int my_array[宽度][高度];

我怎样才能在 Python 中做到这一点

最佳答案

你可以使用 numpy:

import numpy as np
my_array = np.zeros([height, width])

例如:

>>> np.zeros([3, 5])
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

请注意,如果您特别需要整数,则应使用dtype 参数

>>> np.zeros([3, 5], dtype=int)
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

关于python - 在 Python 3 中有效地初始化大小为 n*m 的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405342/

相关文章:

python - 使 django 应用程序在 127.0.0.1 :8000 accessible everywhere? 上运行

javascript - 从对象数组中查找对象索引的最佳方法是什么 - javascript

c++ - 结构类型元素数组的问题

javascript获取非空JSON子数组的计数

python - 我如何删除 python 2.7,因为我已经在 ubuntu 上安装了 3.6.5?

python - 名称错误 : name 'List' is not defined

python - 如何处理 Pandas 中的 SettingWithCopyWarning

python - GAE Python GCS 文件名访问旧文件

python - 迭代器卡住

python - 将 OAuth 与 Google App Engine 结合使用的用户信息