2

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 }};
3
  • Wild guess here from *Nix land: Array[Array[int]]([[1, 2, 3], [4, 5, 6]]) Commented Jan 24, 2019 at 6:28
  • relevant: grokbase.com/t/python/ironpython-users/095vyfwt24/… so try: Array[Array[int]]((Array[int]((1,2,3)), (Array[int]((4,5,6))) Commented Jan 24, 2019 at 6:30
  • @juanpa.arrivillaga b = Array[Array[int]]([Array[int]([1,2,3]), Array[int]([4,5,6])]) works. But how can I write a python function that converts a jagged array which has n dimensions? Commented Jan 24, 2019 at 7:22

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.