I would like to init a .NET jagged array from Python using the pythonnet packages. For an one dimensional array I can do it like that:
import clr
from System import Array
a = Array[int]([1, 2, 3])
But how can I do that for jagged array? So let's assume I've in python the following list of list:
[[1, 2, 3], [4, 5, 6]]
In C# I would do it like that:
int[][] a = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }};
In Python it can be done like that:
b = Array[Array[int]]([Array[int]([1,2,3]), Array[int]([4,5,6])])
or if you define a helper function:
def asnetarray(x, defaulttype):
if type(x) is list:
if any([type(xi) is list for xi in x]):
# Array of array
return asnetarray([asnetarray(xi, defaulttype) for xi in x], defaulttype)
elif x:
# Array
return Array[type(x[1])](x)
else:
# Empty array
return Array[defaulttype]([])
else:
# Single element
return Array[type(x)]([x])
then this can be used as:
# int[][]
b = asnetarray([[1, 2], [3, 4]], int)
# int[][][]
c = asnetarray([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], int)