python - IronPython 中二维类型数组的内联初始化

标签 python ironpython

我有一个关于 IronPython 中类型化数组初始化的问题。我想在 IronPython 中初始化内联类型二维数组。
在 IronPython 中,我发现了如何初始化简单类型数组:

pythonTypedArray = Array[int]([0, 1, 2, 3, 4])

以及如何初始化数组的类型化数组:

pythonTypedArrayOfArrays = Array[Array[int]]([Array[int]([0, 1]), Array[int]([2, 3])])

例如,在 C# 中我可以这样做:

int[,] twoDimensionalArray = new int[,] { {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9} };

我可以在 IronPython 中初始化内联二维类型数组吗?如果不是,在 IronPython 中初始化二维类型数组的最佳方法是什么?

最佳答案

所以,你需要一个矩阵。在Python中可以通过这样做来实现:

matrix = [[0 for x in range(w)] for y in range(h)] 

或者使用numpy (您可以通过运行pip install numpy来安装它):

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

在 numpy 中,用随机数生成矩阵非常简单:

>>> import numpy as np
>>> np.random.rand(2,3)
array([[ 0.22568268,  0.0053246 ,  0.41282024],
       [ 0.68824936,  0.68086462,  0.6854153 ]])

IMO,每当你需要矩阵时,你都想使用 numpy,因为它有一些很好的方法可以真正帮助你处理它们。


//编辑:由于您添加了更多上下文,因此在 IronPython 中您可以通过执行以下操作创建数组的数组:

array = Array[Array[int]]( ( (1,2), (3,4) ) )

或者您可以创建多维数组,方法是使用 Array.CreateInstance 传递类型作为第一个参数,后跟维度大小:

array = Array.CreateInstance(int, 2, 3)

您可以随时阅读the docs当您需要更多信息时

关于python - IronPython 中二维类型数组的内联初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44905949/

相关文章:

python - python进程返回代码-9是什么意思?

c# - 在经典库中使用类时 IronPython 返回错误类型

Python 整数意外结果

python - 按较低级别的值过滤多级数据帧

python - QHBoxLayout 以不同的顺序添加小部件

python - 应用程序注册表未就绪 : Apps aren't loaded yet

python - Unicode 编码、.txt 和阿拉伯语(从右到左)脚本

ironpython - 为什么 IronPython 在构建为 exe 时导入模块比作为脚本慢得多?

python - 我的 ipy.exe 在哪里?

python - IronPython WPF 加载新窗口